package com.ojoin.trade.supplyloan_core.web.service.impl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ojoin.trade.common.utils.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import com.ojoin.trade.bpm.web.service.BpmTaskService;
import com.ojoin.trade.common.constdef.IConstDef;
import com.ojoin.trade.common.exception.BusinessException;
import com.ojoin.trade.common.exception.IPayNowException;
import com.ojoin.trade.common.utils.excel.ExcelTmpl;
import com.ojoin.trade.common.web.domain.NotificationTemplate;
import com.ojoin.trade.common.web.domain.TbUploadFile;
import com.ojoin.trade.common.web.domain.TbWeekend;
import com.ojoin.trade.common.web.service.TbUploadFileService;
import com.ojoin.trade.common.web.service.TbWeekEndService;
import com.ojoin.trade.common.web.service.impl.NotificationTemplateService;
import com.ojoin.trade.common_core.web.domain.TbMerchantInfo;
import com.ojoin.trade.common_core.web.domain.TbMerchantUser;
import com.ojoin.trade.common_core.web.domain.TbMerchantuserExceptionorder;
import com.ojoin.trade.common_core.web.domain.TbMerchantuserFinaccountVo;
import com.ojoin.trade.common_core.web.domain.TbTransferTokenStatus;
import com.ojoin.trade.common_core.web.domain.TransferErrorStatusInfo;
import com.ojoin.trade.common_core.web.service.AccountBaseService;
import com.ojoin.trade.common_core.web.service.MerchantUserBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantInfoBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantuserExceptionorderBaseService;
import com.ojoin.trade.common_core.web.service.TbMerchantuserFinaccountService;
import com.ojoin.trade.common_core.web.service.TransferTokenStatusService;
import com.ojoin.trade.common_core.web.service.impl.DataVersionValidationService;
import com.ojoin.trade.supplyloan_core.constdef.ISLConstDef;
import com.ojoin.trade.supplyloan_core.web.domain.SLDailyCreditVO;
import com.ojoin.trade.supplyloan_core.web.domain.SLDailyRefundVO;
import com.ojoin.trade.supplyloan_core.web.domain.SLDailyStatVO;
import com.ojoin.trade.supplyloan_core.web.domain.SlContractInfoCheckReport;
import com.ojoin.trade.supplyloan_core.web.domain.SlCreditRenewedVo;
import com.ojoin.trade.supplyloan_core.web.domain.SlDailyBalanceReport;
import com.ojoin.trade.supplyloan_core.web.domain.SlDailyReportVO;
import com.ojoin.trade.supplyloan_core.web.domain.TbCatchdataStrategy;
import com.ojoin.trade.supplyloan_core.web.domain.TbRedo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlCreditControll;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlCreditForFloatVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlCreditLogForExcelVO;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlFinanceinfo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlFinanceinfoVO;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanApplication;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanCreditLog;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanCreditLogForFront;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanCreditVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanCreditVoForFront;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanDailyBillVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanFloat;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanInfo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanInfoLog;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanRefundLog;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlLoanRefundVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlNotPayBackCredit;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUser;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlPlatformUserWithdrawVO;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlProcessInfo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlProcessInfoVO;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlRefundCreditVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlRefundForFrontVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlRefundVo;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlStattaskRunresult;
import com.ojoin.trade.supplyloan_core.web.domain.TbSlStatusCreditLogVo;
import com.ojoin.trade.supplyloan_core.web.service.TbCatchdataStrategyService;
import com.ojoin.trade.supplyloan_core.web.service.TbRedoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSLLoanInfoLogService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlCreditCtrollService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlFinanceinfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanApplicationService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanCreditService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanFloatService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanRefundService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlLoanStatTotalService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlPlatformUserService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlProcessInfoService;
import com.ojoin.trade.supplyloan_core.web.service.TbSlStattaskRunresultService;

/**
 * Created with IntelliJ IDEA.
 * User: Administrator
 * Date: 15-10-30
 * Time: 下午1:34
 * To change this template use File | Settings | File Templates.
 */

@Service
public class TbSlLoanServiceImpl implements TbSlLoanService {

	 @Autowired
	private BpmTaskService bpmTaskService;

     @Autowired
   private   TbSlLoanInfoService loanInfoService;
    @Autowired
   private TbSlLoanApplicationService applicationService;

    @Autowired
   private   TbSlStattaskRunresultService taskrunresultService;

    @Autowired
    private TbSlLoanStatTotalService  loanStatTotalService;

    @Autowired
    private TbSlLoanCreditService tbSlLoanCreditService;

    @Autowired
    private AccountBaseService accountbaseservice;

    @Autowired
   private TbSlLoanRefundService tbSlLoanRefundService;

    @Autowired
   private   MerchantUserBaseService userBaseService;

    @Autowired
  private   TbMerchantuserFinaccountService finaccountService;

    @Autowired
    private TbSlLoanApplicationService slservice;

     @Autowired
     private  TbSlFinanceinfoService financeinfoService;

    @Autowired
    private TbSlPlatformUserService tbSlPlatformUserService;

    @Autowired
    private TbSLLoanInfoLogService tbSLLoanInfoLogService;

    @Autowired
    private DataVersionValidationService dataVersionValidationService;

    @Autowired
    private TbMerchantInfoBaseService infoBaseService;
    
    @Autowired
    private TbSlLoanInfoService tbSlLoanInfoService;

    @Autowired
    protected TbSlLoanFloatService tbSlLoanFloatService;

    @Autowired
    private TbUploadFileService uploadFileService;

    @Autowired
    private TbSlProcessInfoService tbSlProcessInfoService;

    @Autowired
    private TbSlCreditCtrollService tbSlCreditCtrollService;

    @Autowired
    private TbWeekEndService tbWeekEndService;

    @Autowired
    private TbMerchantInfoBaseService tbMerchantInfoBaseService;

    @Autowired
    private TransferTokenStatusService transferTokenStatusService;

    @Autowired
    private TbRedoService tbRedoService;

    @Autowired
    private TbMerchantuserExceptionorderBaseService merchantuserExceptionorderBaseService;
    
    @Autowired
    private NotificationTemplateService notificationTemplateService;
    
    @Autowired
	private TbCatchdataStrategyService catchdataStrategyService;
    /**
     *    算法的基本思想：
     *
     *    获取商户当天的统计值*折扣率>授信的可贷额度，今日可提限额为= 授信的可贷额度-未还贷款额度
     *   否则 今日可提限额为= 统计值*折扣率-未还贷款额度
     */
    @Override
    public String getMaxLoanAmount(int joinid,String type) throws BusinessException {
        TbSlLoanApplication applicationvo=this.applicationService.queryTbSlApplicationByJoinId(joinid);

        TbSlLoanInfo info = loanInfoService.queryLoanInfoByJoinid(joinid);

        List<TbSlPlatformUserWithdrawVO> listByJoinuserId = tbSlPlatformUserService.selectPlatformUserWithdrawListByJoinuserId(joinid);

        long amount=0;
        long notpayamount=getAlsoLoanAmount(joinid);
        double discountdouble=0;
        long totalUnsettleInstoreorder=0;
        long  totalUnenterinRefundorder=0;
        long   totalUnpaySettleorder=0;
        double totalOrderAmount=0;
        long totalOrderAmountlong=0;

        try{
//            int  isexist=tbSlPlatformUserService.isExistPausedPlatformUserByJoinuserId(joinid);
//            if(isexist>0){
//               throw new BusinessException("平台更新审核中，暂停放款");
//            }
            if(applicationvo!=null){
                if(applicationvo.getLoanstatus()!= ISLConstDef.SLLOANSTATUS_MATERIALPASSED) {
                    throw new BusinessException("业务审核中");
                }
                if(applicationvo.getCreditEndDate() == null || applicationvo.getCreditEndDate().length() < 10) {
                	throw new BusinessException("保理合同到期日期有误，请检查.");
                }
                	
                String creditEndDate = applicationvo.getCreditEndDate();
                if (creditEndDate.compareTo(TimeUtils.getCurDate()) < 0){
                    throw new BusinessException("合同已经到期");
                }
            }else{
               throw new BusinessException("未开通");
            }

          List<TbSlStattaskRunresult> resultlist= taskrunresultService.queryFailureByJoinid(joinid);
            if(!CommonUtils.isEmpty(resultlist)){


           throw new BusinessException("您的融资业务暂时关闭，原因可能是：1、您注册时填写的公司名称与您在电商平台所留的公司名称不一致。2、您在电商平台的结算户未变更为我们给您提供的民生银行托管账户。3、您电商平台的账号密码有误，请及时到“平台管理”页面下更改。若仍有问题请拨打咨询电话：010-63105899");

            }
            if(CommonUtils.isEmpty(listByJoinuserId)){
              return "0";
            }
          for(TbSlPlatformUserWithdrawVO vo:listByJoinuserId){
             if(ISLConstDef.MERCHANT_TYPE.equals(type)) {
        	     amount += getMaxByPlatform(vo);
             }else if(ISLConstDef.OPERATOR_TYPE.equals(type)){
                  amount +=getMaxByPlatformForOperator(vo);
              }else{
                 amount +=getMaxByPlatformForFisttrial(vo);
             }
          }
          return new Long(amount).toString();

        }catch (Exception e){
        throw  e;


        }

    }

    public long getAlsoLoanAmount(int joinid)throws  BusinessException{

        String amount= this.tbSlLoanCreditService.querySumApplyLoanByJoinid(joinid);
        if(StringUtils.isEmpty(amount)){
            return 0;
        }
        return new Long(amount);

    }


    @Override
    public void updateForfirsttrialSuccess(int id, int idofcompany, String ts,String loanVoucher,String paymentNotice,int joinid,String contract,String loanregist) throws BusinessException {
          tbSlProcessInfoService.lockById(id);
          dataVersionValidationService.validateVO(id,"tb_sl_process_info",ts);
          TbSlProcessInfo vo=tbSlProcessInfoService.queryById(id);
          BigDecimal loanamount=new BigDecimal(vo.getAmount());
          BigDecimal amount=new BigDecimal(getMaxLoanAmount(joinid,ISLConstDef.FIRSTTRIAL_TYPE));
          if(loanamount.doubleValue()>amount.doubleValue()){
              throw new BusinessException("贷款金额" + loanamount +"大于可贷最大金额" + amount);
          }
           Map<String,Object> paramap=new HashMap<String ,Object>();
           paramap.put("process_info_id",id);
           paramap.put("creditstatus",IConstDef.LOAN_TYPE_OF_FIRSTTRIAL) ;
           paramap.put("idOfTbFactoryingCompany",idofcompany);
           paramap.put("rowUpdateTime",ts);
           paramap.put("loanVoucher",loanVoucher);
           paramap.put("paymentNotice",paymentNotice);
           paramap.put("contract",contract);
           paramap.put("loanregist",loanregist);
           this.tbSlLoanCreditService.updateCreditLogForBatch(paramap);   //根据流程id更新贷款数据
           Map<String,Object> map=new HashMap<>();
           map.put("id",id);
           map.put("loanStatus",IConstDef.LOAN_TYPE_OF_FIRSTTRIAL);
        this.tbSlProcessInfoService.updateTbSlProcessInfo(map);
        if(!CommonUtils.isEmpty(loanVoucher))
        uploadFileService.updateStatusById(CommonUtils.getInt(loanVoucher),IConstDef.UPLOADSTATUS_COMMITED);
        if(!CommonUtils.isEmpty(paymentNotice))
        uploadFileService.updateStatusById(CommonUtils.getInt(paymentNotice),IConstDef.UPLOADSTATUS_COMMITED);
        if(!CommonUtils.isEmpty(contract)){
            uploadFileService.updateStatusById(CommonUtils.getInt(contract),IConstDef.UPLOADSTATUS_COMMITED);
        }
        if(!CommonUtils.isEmpty(loanregist)){
            uploadFileService.updateStatusById(CommonUtils.getInt(loanregist),IConstDef.UPLOADSTATUS_COMMITED);
        }
        
    }

    @Override
    public void updateForRefuseLoan(int id, int idofcompany, String memo, String ts) throws BusinessException {
        tbSlLoanCreditService.lockById(id);
        dataVersionValidationService.validateVO(id,"tb_sl_loan_credit_log",ts);
        Map<String,Object>  parammap=new HashMap<String, Object>();
        parammap.put("id",id);
        parammap.put("idOfTbFactoryingCompany",idofcompany);
        parammap.put("memo",memo);
        parammap.put("creditstatus",IConstDef.LOAN_TYPE_OF_REFUSE);
        parammap.put("refuseLoanTime",TimeUtils.getCurDate());
        parammap.put("rowUpdateTime",ts);
        this.tbSlLoanCreditService.updateTbSlLoanCredit(parammap);

    }

    @Override
    public void updateForRealLoan(int processInfoId, int idOfTbFactoryingOperator, String mhtnofrom, String payPasswd,Integer idofLoanInfo,String ts,String tsOfLoanInfo,String voucher,String taskid, String processid) throws BusinessException {
        tbSlProcessInfoService.lockById(processInfoId);
        dataVersionValidationService.validateVO(processInfoId,"tb_sl_process_info",ts);
        TbSlProcessInfo vo=tbSlProcessInfoService.queryById(processInfoId);
        List<TbSlStatusCreditLogVo> creditLogList=this.tbSlLoanCreditService.queryCreditByProcessid(processInfoId);
        if(CommonUtils.isEmpty(creditLogList)){
            throw  new BusinessException("查询商户的该贷款记录有误，请重新刷新界面");
        }
        String amountstr=vo.getAmount();
        if(StringUtils.isEmpty(amountstr)){
            throw  new BusinessException("查询商户的该贷款额度有误，请重新刷新界面");
        }
        int joinid=vo.getUserIdOfJoinOfDebtor();
        long amount=Long.parseLong(amountstr);
//        String canloanamount=getMaxLoanAmount(joinid,ISLConstDef.OPERATOR_TYPE);
//        long canloan=CommonUtils.getLong(canloanamount);
//        if(canloan<amount){
//            throw new BusinessException("贷款金额不能大于可贷金额");
//        }
        ;

        String mhtnoto=vo.getUserIdOfIPayNowOfDebtor();
        String order_id=UUIDUtils.create();
        for(TbSlStatusCreditLogVo creditLogVo:creditLogList){
        TbSlPlatformUser user=this.tbSlPlatformUserService.selectPlatformById(creditLogVo.getIdOfPlatform());
         if(CommonUtils.isEmpty(user)){
             throw  new BusinessException("未查询到贷款对应平台的信息");
         }
            updateRealLoan(creditLogVo.getId(),joinid,user.getLoanPeriod(),order_id,idOfTbFactoryingOperator,mhtnofrom,voucher);
        }

        updateLoanStat(amount,joinid,idofLoanInfo,tsOfLoanInfo);
        Map<String,Object> map=new HashMap<>();
        map.put("id",processInfoId);
        map.put("loanStatus",IConstDef.LOAN_TYPE_OF_NOTPAY);
        map.put("loanDate",TimeUtils.getCurDate());
        tbSlProcessInfoService.updateTbSlProcessInfo(map);
        if(!CommonUtils.isEmpty(voucher)){
             uploadFileService.updateStatusById(CommonUtils.getInt(voucher),IConstDef.UPLOADSTATUS_COMMITED);
        }
      if(CommonUtils.isEmpty(creditLogList.get(0).getIdOfBankAcc())){
        try{
       List list=this.accountbaseservice.rechargeAccountBalance(mhtnofrom,IConstDef.ACCTYPE_BASE,payPasswd,mhtnoto,IConstDef.ACCTYPE_BASE,new Long(amount).toString(),"放款金额(分)："+amount,order_id);
        }catch(Exception e){
         if(e instanceof IPayNowException){
             TbRedo redo=new TbRedo();
             redo.setApplyDate(TimeUtils.getCurDate());
             redo.setOrderId(order_id);

             Map<String,Object> parammap=new HashMap<>();
             parammap.put("processInfoId",processInfoId);
             parammap.put("idOfTbFactoryingOperator",idOfTbFactoryingOperator);
             parammap.put("mhtnofrom",mhtnofrom);
             parammap.put("idofLoanInfo",idofLoanInfo);
             parammap.put("ts",ts);
             parammap.put("tsOfLoanInfo",tsOfLoanInfo);
             parammap.put("voucher",voucher);
             parammap.put("taskid",taskid);
             parammap.put("processid",processid);
             byte[] bytes=CommonUtils.serialize(parammap);
             redo.setBusinessType(IConstDef.LOAN);
             redo.setParamstr(bytes);
             redo.setIsdo(IConstDef.UNDO);
             tbRedoService.insertTbRedo(redo);
             TbMerchantuserExceptionorder ordervo=new TbMerchantuserExceptionorder();
             ordervo.setOrderid(order_id);
             ordervo.setAccountStatus(IConstDef.ACCOUNT_STATUS_FREEZE);
             ordervo.setIdOfTbMerchantUser(joinid);
             ordervo.setBusinessType(IConstDef.EXCEPTIONORDER_TYPE_RECHARGE);
             ordervo.setOrderTime(TimeUtils.getCurDateTime());
             merchantuserExceptionorderBaseService.insertMerchantuserExceptionorder(ordervo);
         }
            throw  e;
        }
        }
        if(!CommonUtils.isDev()){
       TbSlProcessInfoVO processInfoVO=tbSlProcessInfoService.queryMobileByProcessid(processInfoId);
       if(!CommonUtils.isEmpty(processInfoVO)){
           String mobile=processInfoVO.getMobile();
           if(!CommonUtils.isEmpty(mobile)){
        	   sendMsg("%applydate%", processInfoVO.getApplyDate(), ISLConstDef.LOAN_PASS, mobile);
           }
       }
        }
        if(!CommonUtils.isEmpty(taskid)){
        Map<String,Object> taskVars=new HashMap();
        taskVars.put("pass", "1");
        bpmTaskService.complete(taskid, processid,"放款成功", taskVars);

        }
    }



    @Override
    public void updateForRedoRealLoan(int processInfoId, int idOfTbFactoryingOperator, String mhtnofrom, Integer idofLoanInfo,String ts,String tsOfLoanInfo,String voucher,String applydate,String orderid,String taskid, String processid) throws BusinessException {
        tbSlProcessInfoService.lockById(processInfoId);
        dataVersionValidationService.validateVO(processInfoId,"tb_sl_process_info",ts);
        TbSlProcessInfo vo=tbSlProcessInfoService.queryById(processInfoId);
        List<TbSlStatusCreditLogVo> creditLogList=this.tbSlLoanCreditService.queryCreditByProcessid(processInfoId);
        if(CommonUtils.isEmpty(creditLogList)){
            throw  new BusinessException("查询商户的该贷款记录有误，请重新刷新界面");
        }
        String amountstr=vo.getAmount();
        if(StringUtils.isEmpty(amountstr)){
            throw  new BusinessException("查询商户的该贷款额度有误，请重新刷新界面");
        }
        int joinid=vo.getUserIdOfJoinOfDebtor();
        long amount=Long.parseLong(amountstr);
        String canloanamount=getMaxLoanAmount(joinid,ISLConstDef.OPERATOR_TYPE);
        long canloan=CommonUtils.getLong(canloanamount);
        if(canloan<amount){
            throw new BusinessException("贷款金额不能大于可贷金额");
        }

        String mhtnoto=vo.getUserIdOfIPayNowOfDebtor();
        for(TbSlStatusCreditLogVo creditLogVo:creditLogList){
            TbSlPlatformUser user=this.tbSlPlatformUserService.selectPlatformById(creditLogVo.getIdOfPlatform());
            if(CommonUtils.isEmpty(user)){
                throw  new BusinessException("未查询到贷款对应平台的信息");
            }
            updateRealLoan(creditLogVo.getId(),joinid,user.getLoanPeriod(),orderid,idOfTbFactoryingOperator,mhtnofrom,voucher);
        }

        updateLoanStat(amount,joinid,idofLoanInfo,tsOfLoanInfo);
        Map<String,Object> map=new HashMap<>();
        map.put("id",processInfoId);
        map.put("loanStatus",IConstDef.LOAN_TYPE_OF_NOTPAY);
        map.put("loanDate",TimeUtils.getCurDate());
        tbSlProcessInfoService.updateTbSlProcessInfo(map);
        if(!CommonUtils.isEmpty(voucher)){
            uploadFileService.updateStatusById(CommonUtils.getInt(voucher),IConstDef.UPLOADSTATUS_COMMITED);
        }

        if(!CommonUtils.isDev()){
            TbSlProcessInfoVO processInfoVO=tbSlProcessInfoService.queryMobileByProcessid(processInfoId);
            if(!CommonUtils.isEmpty(processInfoVO)){
                String mobile=processInfoVO.getMobile();
                if(!CommonUtils.isEmpty(mobile)){
                	sendMsg("%applydate%", processInfoVO.getApplyDate(), ISLConstDef.LOAN_PASS, mobile);

                }
            }
        }
        if(!CommonUtils.isEmpty(taskid)){
        Map<String,Object> taskVars=new HashMap();
        taskVars.put("pass", "1");
        bpmTaskService.complete(taskid, processid,"放款成功", taskVars);
        }

        transferTokenStatusService.updateTransferTokenStatus(orderid,IConstDef.TRANSFERSTATUS_SUCCESS,"处理成功");
        tbRedoService.updateTbRedo(orderid);
        TbMerchantuserExceptionorder ordervo=new TbMerchantuserExceptionorder();
        ordervo.setHandleTime(TimeUtils.getCurDateTime());
        ordervo.setHandleMemo("处理完毕");
        ordervo.setOrderid(orderid);
        ordervo.setAccountStatus(IConstDef.ACCOUNT_STATUS_UNFREEZE);
        merchantuserExceptionorderBaseService.updateVOByOrderId(ordervo);
    }

    @Override
    public Long updateForRepayLoan(int joinid, List<TbSlNotPayBackCredit> listvo,TbSlLoanInfo loaninfovo,String pwd,String accamount, String repayAcccountType) throws BusinessException {
        boolean isfrezz=merchantuserExceptionorderBaseService.isFreezeByJoinuserID(joinid);
        if(isfrezz){
            throw new BusinessException("账户状态为锁定，请联系保理公司");
        }

        if(isDaySpecial()){
            throw new BusinessException("节假日期间不能还款");
        }
        if(!CommonUtils.expireTime()){
            throw new BusinessException("请于当日下午15:00前还款");
        }
        if(CommonUtils.isEmpty(joinid)||CommonUtils.isEmpty(listvo)){
            return (long)0;
        }
        long  totalamount=0;
        long totalpayrate=0;
//        List<TbSlLoanRefundLog> refundLogs=new ArrayList<TbSlLoanRefundLog>();
        long amount=0;
        String orderid=UUIDUtils.create();
        String  userIdOfIPayNowOfDebtor=null;
        String  userIdOfIPayNowOfCreditor=null;

        for(TbSlNotPayBackCredit tbSlNotPayBackCredit:listvo){
            tbSlLoanCreditService.lockById(tbSlNotPayBackCredit.getId());
            dataVersionValidationService.validateVO(tbSlNotPayBackCredit.getId(),"tb_sl_loan_credit_log",tbSlNotPayBackCredit.getRowUpdateTime());
           TbSlLoanCreditLog creditLog=tbSlLoanCreditService.queryCreditLogById(tbSlNotPayBackCredit.getId());
            if(CommonUtils.isEmpty(userIdOfIPayNowOfCreditor)){
                userIdOfIPayNowOfCreditor=creditLog.getUserIdOfIPayNowOfCreditor();
            }
            if(CommonUtils.isEmpty(userIdOfIPayNowOfDebtor)){
                userIdOfIPayNowOfDebtor=creditLog.getUserIdOfIPayNowOfDebtor();
            }
         amount=amount+ updateRepayOneByManial(loaninfovo,creditLog, joinid, orderid,null);
        }
        if(amount>CommonUtils.getLong(accamount)){
            throw new BusinessException("账户余额不足，请充值后重新还款");
        }
        updateLoanLog(loaninfovo);
        try{
        	if (!CommonUtils.isDev()) {
		         //根据参数repayAcccountType来决定从基本户还款还是业务户还款
		        List rechargelist=this.accountbaseservice.rechargeAccountBalance(userIdOfIPayNowOfDebtor,repayAcccountType,pwd,userIdOfIPayNowOfCreditor,IConstDef.ACCTYPE_BASE,new Long(amount).toString(),"还款",orderid);
        	}
        }catch (Exception e){
            if(e instanceof IPayNowException){
                TbRedo redo=new TbRedo();
                redo.setApplyDate(TimeUtils.getCurDate());
                redo.setOrderId(orderid);
                Map<String,Object> map=new HashMap<>();
                map.put("accamount",accamount);
                map.put("joinid",joinid);
                map.put("listvo",listvo);
                map.put("loaninfovo",loaninfovo);
                map.put("repayAcccountType",repayAcccountType);
                byte[] bytes=CommonUtils.serialize(map);
                redo.setBusinessType(IConstDef.REPAYBYSELF);
                redo.setParamstr(bytes);
                redo.setIsdo(IConstDef.UNDO);
                tbRedoService.insertTbRedo(redo);
                TbMerchantuserExceptionorder ordervo=new TbMerchantuserExceptionorder();
                ordervo.setOrderid(orderid);
                ordervo.setAccountStatus(IConstDef.ACCOUNT_STATUS_FREEZE);
                ordervo.setIdOfTbMerchantUser(joinid);
                ordervo.setBusinessType(IConstDef.EXCEPTIONORDER_TYPE_RECHARGE);
                ordervo.setOrderTime(TimeUtils.getCurDateTime());
                merchantuserExceptionorderBaseService.insertMerchantuserExceptionorder(ordervo);
            }
             throw e;

                    }
        if(!CommonUtils.isDev()){
            TbMerchantInfo user=tbMerchantInfoBaseService.queryInfoByJoinId(joinid);
            if(!CommonUtils.isEmpty(user)){
                String mobile=user.getMobile();
                if(!CommonUtils.isEmpty(mobile))
                	sendMsg("%money%", CommonUtils.getYuanByLong(amount)+"", ISLConstDef.ACCOUNT_OUT, mobile);
            }


        }

        return amount;
    }

    @Override
    public void updateForReDoRepayLoan(int joinid, List<TbSlNotPayBackCredit> listvo, TbSlLoanInfo loaninfovo, String accamount, String applydate, String repayAcccountType, String orderId) throws BusinessException {
        if(isDaySpecial()){
            throw new BusinessException("节假日期间不能还款");
        }

        if(CommonUtils.isEmpty(joinid)||CommonUtils.isEmpty(listvo)){
            return ;
        }
        long  totalamount=0;
        long totalpayrate=0;
//        List<TbSlLoanRefundLog> refundLogs=new ArrayList<TbSlLoanRefundLog>();
        long amount=0;
        String  userIdOfIPayNowOfDebtor=null;
        String  userIdOfIPayNowOfCreditor=null;

        for(TbSlNotPayBackCredit tbSlNotPayBackCredit:listvo){
            tbSlLoanCreditService.lockById(tbSlNotPayBackCredit.getId());
            dataVersionValidationService.validateVO(tbSlNotPayBackCredit.getId(),"tb_sl_loan_credit_log",tbSlNotPayBackCredit.getRowUpdateTime());
            TbSlLoanCreditLog creditLog=tbSlLoanCreditService.queryCreditLogById(tbSlNotPayBackCredit.getId());
            if(CommonUtils.isEmpty(userIdOfIPayNowOfCreditor)){
                userIdOfIPayNowOfCreditor=creditLog.getUserIdOfIPayNowOfCreditor();
            }
            if(CommonUtils.isEmpty(userIdOfIPayNowOfDebtor)){
                userIdOfIPayNowOfDebtor=creditLog.getUserIdOfIPayNowOfDebtor();
            }
            amount=amount+ updateRepayOneByManial(loaninfovo,creditLog, joinid, orderId,applydate);
        }
        if(amount>CommonUtils.getLong(accamount)){
            throw new BusinessException("账户余额不足，请充值后重新还款");
        }
        updateLoanLog(loaninfovo);
        if(!CommonUtils.isDev()){
            TbMerchantInfo user=tbMerchantInfoBaseService.queryInfoByJoinId(joinid);
            if(!CommonUtils.isEmpty(user)){
                String mobile=user.getMobile();
                if(!CommonUtils.isEmpty(mobile))
                	sendMsg("%money%", CommonUtils.getYuanByLong(amount)+"", ISLConstDef.ACCOUNT_OUT, mobile);
            }
        }

        transferTokenStatusService.updateTransferTokenStatus(orderId,IConstDef.TRANSFERSTATUS_SUCCESS,"处理成功");
        tbRedoService.updateTbRedo(orderId);
        TbMerchantuserExceptionorder ordervo=new TbMerchantuserExceptionorder();
        ordervo.setHandleTime(TimeUtils.getCurDateTime());
        ordervo.setHandleMemo("处理完毕");
        ordervo.setOrderid(orderId);
        ordervo.setAccountStatus(IConstDef.ACCOUNT_STATUS_UNFREEZE);
        merchantuserExceptionorderBaseService.updateVOByOrderId(ordervo);

    }

    @Override
    public long updateRepayOneByManial(TbSlLoanInfo loanInfo,TbSlLoanCreditLog creditLog, int joinid, String order_id,String applydate)throws BusinessException {
        if(creditLog.getCreditstatus()==IConstDef.LOAN_TYPE_OF_PAYALL) {
           return 0;
        }
        long amount=0;
        long totalamount=0;
        long totalpayrate=0;
        long totalpayfee=0;
        long totalrenewrate=0;
        long totalrenewfee=0;
        long totalpenalty=0;
        long totalrenewedamount=0;
        String totalNotPaybackAmount=creditLog.getTotalNotPaybackAmount();
        String totalNotPaybackFee=creditLog.getTotalNotPaybackFee();
        String totalNotPaybackRate=creditLog.getTotalNotPaybackRate();
        String  totalNotPaybackRenewedRate=creditLog.getTotalNotPaybackRenewedRate();
        String totalNotPaybackRenewedFee=creditLog.getTotalNotPaybackRenewedFee();
        String  totalNotPaybackPenalty=creditLog.getTotalNotPaybackPenalty();
        String totalNotPaybackRenewedAmount=creditLog.getTotalNotPaybackRenewedAmount();
        if(!StringUtils.isEmpty(totalNotPaybackAmount)){
            totalamount=totalamount+Long.parseLong(totalNotPaybackAmount);
            amount=amount+Long.parseLong(totalNotPaybackAmount);
        }
        if(!StringUtils.isEmpty(totalNotPaybackFee)){
            totalpayfee=totalpayfee+Long.parseLong(totalNotPaybackFee);
            amount=amount+Long.parseLong(totalNotPaybackFee);
        }
        if(!StringUtils.isEmpty(totalNotPaybackRate)) {
            totalpayrate=totalpayrate+Long.parseLong(totalNotPaybackRate);
            amount=amount+totalpayrate;
        }
       if(!StringUtils.isEmpty(totalNotPaybackRenewedRate)) {
           totalrenewrate=totalrenewrate+Long.parseLong(totalNotPaybackRenewedRate);
           amount=amount+totalrenewrate;
       }
        if(!StringUtils.isEmpty(totalNotPaybackRenewedFee)){
            totalrenewfee=totalrenewfee+Long.parseLong(totalNotPaybackRenewedFee);
            amount=amount+totalrenewfee;
        }
        if(!StringUtils.isEmpty(totalNotPaybackPenalty)){
            totalpenalty=totalpenalty+Long.parseLong(totalNotPaybackPenalty);
            amount=amount+totalpenalty;
        }
        if(!StringUtils.isEmpty(totalNotPaybackRenewedAmount)&&TimeUtils.getCurDate().compareTo(creditLog.getLastRefundTime())>0){
            totalrenewedamount=totalrenewedamount+Long.parseLong(totalNotPaybackRenewedAmount);
            amount=amount+ totalrenewedamount;

        }


        TbSlLoanRefundLog refundLog=new TbSlLoanRefundLog();
        refundLog.setIdSlLoanCreditLog(creditLog.getId());
        if(!CommonUtils.isEmpty(applydate)){
            refundLog.setRefundDate(applydate);
        }else{
        refundLog.setRefundDate(TimeUtils.getCurDate());
        }
        refundLog.setRefundOrderId(order_id);
        refundLog.setUserIdOfJoinOfDebtor(creditLog.getUserIdOfJoinOfDebtor());
        refundLog.setUserIdOfJoinOfCreditor(creditLog.getUserIdOfJoinOfCreditor());
        refundLog.setRefundPrinciple(creditLog.getTotalNotPaybackAmount());
        refundLog.setRefundPenalty(creditLog.getTotalNotPaybackPenalty());
        refundLog.setRefundRate(creditLog.getTotalNotPaybackRate());
        refundLog.setRefundFee(creditLog.getTotalNotPaybackFee());
        refundLog.setRefundRenewedFee(creditLog.getTotalNotPaybackRenewedFee());
        refundLog.setRefundRenewedRate(creditLog.getTotalNotPaybackRenewedRate());
        refundLog.setRefundRenewedAmount(new Long(totalrenewedamount).toString());
        refundLog.setShouldRefundPrinciple(creditLog.getTotalNotPaybackAmount());
        refundLog.setShouldRefundRate(new Long(totalpayfee+totalpayrate+totalrenewfee+totalrenewrate+totalpenalty).toString());
         refundLog.setRefundAmount(new Long(amount).toString());
        refundLog.setNormalIntrest(new Long(totalpayfee+totalpayrate).toString());
        refundLog.setRenewedAmount(new Long(totalrenewedamount).toString());
        refundLog.setRenewedIntrest(new Long(totalrenewfee+totalrenewrate).toString());
        refundLog.setPentyIntrest(new Long(totalpenalty).toString());
        //设置
        creditLog.setTotalNotPaybackAmount("0");
        creditLog.setTotalNotPaybackFee("0");
        creditLog.setTotalNotPaybackRate("0");
        creditLog.setTotalNotPaybackPenalty("0");
        creditLog.setTotalNotPaybackRenewedAmount("0");
        creditLog.setTotalNotPaybackRenewedFee("0");
        creditLog.setTotalNotPaybackRenewedRate("0");
        creditLog.setCreditstatus(IConstDef.LOAN_TYPE_OF_PAYALL);
        Map<String,Object> paramap=new HashMap<String, Object>();
        paramap.put("totalNotPaybackAmount",creditLog.getTotalNotPaybackAmount());
        paramap.put("totalNotPaybackFee",creditLog.getTotalNotPaybackFee());
        paramap.put("totalNotPaybackRate",creditLog.getTotalNotPaybackRate());
        paramap.put("totalNotPaybackPenalty",creditLog.getTotalNotPaybackPenalty());
        paramap.put("totalNotPaybackRenewedAmount",creditLog.getTotalNotPaybackRenewedAmount());
        paramap.put("totalNotPaybackRenewedFee",creditLog.getTotalNotPaybackRenewedFee());
        paramap.put("totalNotPaybackRenewedRate",creditLog.getTotalNotPaybackRenewedRate());
        paramap.put("creditstatus",creditLog.getCreditstatus());
        paramap.put("id",creditLog.getId());
        paramap.put("rowUpdateTime",TimeUtils.getDateString(creditLog.getRowUpdateTime()));
          repayLoanStat(loanInfo,totalamount,totalpayrate,totalpayfee
                  ,totalrenewrate,totalrenewfee,totalpenalty,totalrenewedamount,joinid,creditLog.getIdOfPlatform());
        this.tbSlLoanCreditService.updateTbSlLoanCredit(paramap);
        this.tbSlLoanRefundService.insert(refundLog);
          return amount;
    }

    @Override
    public void queryFinanceInfo() throws BusinessException {
        List<TbMerchantuserFinaccountVo>  list=finaccountService.queryFinaccountByType(IConstDef.TYPE_SUPPLYLOAN,IConstDef.CMBC_TYPE);
        if(CommonUtils.isEmpty(list)){
            return;
        }
        for(TbMerchantuserFinaccountVo finaccount:list){
        	String mhtno=finaccount.getMhtno();
        	int joinid=finaccount.getIdOfTbMerchantUser();
        	//天津方鑫商户不做自动还款，直接跳过
        	if (joinid == 123) {
        		continue;
        	}
        	
            try{
            	//查询商户的金融户的余额
            	long accountBalance = accountbaseservice.queryFinanceAccountBanlance(finaccount.getMhtno());
                //账户余额为0不新增任务
                if(accountBalance > 0) {
                    TbSlFinanceinfo infovo=new TbSlFinanceinfo();
                    infovo.setIdOfTbMerchantUser(joinid);
                    infovo.setAmount(CommonUtils.getString(accountBalance));
                    infovo.setCurdate(TimeUtils.getCurDate());
                    infovo.setState(ISLConstDef.SLREFUND_NORUN);
                    financeinfoService.insertSLFinanceInfo(infovo);
                    
                    LogUtils.getSlloanLog().info("新增待还款任务成功, joinuserid->" + joinid + " amount->" + accountBalance);
                }
            }catch (Exception e){
                TbSlFinanceinfo infovo=new TbSlFinanceinfo();
                infovo.setIdOfTbMerchantUser(joinid);
                infovo.setCurdate(TimeUtils.getCurDate());
                infovo.setState(ISLConstDef.SLREFUND_QUERYFAILED);
                infovo.setMemo(e.getMessage());
                financeinfoService.insertSLFinanceInfo(infovo);
                
                LogUtils.getSlloanLog().info("新增待还款任务查询余额失败, joinuserid->" + joinid + " 失败原因->" + e.getMessage());
            }
        }
    }

    /**
     * 计算每个平台的最大可贷额度
     * @param vo
     * @return
     */
    private Long getMaxByPlatform(TbSlPlatformUserWithdrawVO vo ){

        double discount=CommonUtils.getdouble(vo.getDiscount());
        Long maxcount=CommonUtils.getLong(vo.getMaxAmount());
        double canloandou=discount*vo.getTotalAmount()/100;
        long canloanlong=0;
        BigDecimal canloandec=new BigDecimal(canloandou).setScale(0,BigDecimal.ROUND_HALF_UP);
        canloanlong=canloandec.longValue();
        if(canloanlong>maxcount){
            canloanlong=maxcount;
        }
        if(vo.getEnableFlag()=="paused"){
            canloanlong=0;
        }
        Long alsoloan=CommonUtils.getLong(vo.getTotalApplycreditAmount());
        long rateandfee=CommonUtils.getLong(vo.getTotalNotPaybackRateAndFee());
        
        
        TbCatchdataStrategy ca =  catchdataStrategyService.queryByPlatformUserId(vo.getId());
        
        Long lastcancredit = 0L ;
        
        if(!CommonUtils.isEmpty(ca)){
        	if(TbCatchdataStrategy.NOALSOLOAN.equals(ca.getLoanAmountType())){
        		 lastcancredit = canloanlong-rateandfee;
        	}else {
        		lastcancredit = canloanlong-alsoloan-rateandfee;
        	}
        }else {
        	    lastcancredit = canloanlong-alsoloan-rateandfee;
        }
        
        
        LogUtils.getSlloanLog().info(
				"计算平台的最大可贷额度：" +
				"商户九盈id->" + vo.getIdOfTbMerchantUser() + " " +
				"平台id->" + vo.getId() + " " +
				"融资折扣->" + discount + " " +
				"最高限额->" + maxcount + " " +
				"应收账款->" + canloanlong + " " +
				"负债额->" + alsoloan + " " +
				"负债利息->" + rateandfee + " " +
				"可提限额->" + lastcancredit);
		
        return lastcancredit;

    }

    /**给放款的保理员提供计算每个平台的最大可提额度
     *  * @param vo
     * @return
     */
    private Long getMaxByPlatformForOperator(TbSlPlatformUserWithdrawVO vo){
        double discount=CommonUtils.getdouble(vo.getDiscount());
        Long maxcount=CommonUtils.getLong(vo.getMaxAmount());
        double canloandou=discount*vo.getTotalAmount()/100;
        long canloanlong=0;
        BigDecimal canloandec=new BigDecimal(canloandou).setScale(0,BigDecimal.ROUND_HALF_UP);
        canloanlong=canloandec.longValue();
        if(canloanlong>maxcount){
            canloanlong=maxcount;
        }
        Long alsoloan=CommonUtils.getLong(vo.getTotalNotPaybackAmount());
        long rateandfee=CommonUtils.getLong(vo.getTotalNotPaybackRateAndFee());
        
        TbCatchdataStrategy ca =  catchdataStrategyService.queryByPlatformUserId(vo.getId());
        
        Long lastcancredit = 0L ;
        
        if(!CommonUtils.isEmpty(ca)){
        	if(TbCatchdataStrategy.NOALSOLOAN.equals(ca.getLoanAmountType())){
        		 lastcancredit = canloanlong-rateandfee;
        	}else {
        		lastcancredit = canloanlong-alsoloan-rateandfee;
        	}
        }else {
        	    lastcancredit = canloanlong-alsoloan-rateandfee;
        }
        
        return  lastcancredit;
    }

    /**初审的保理员查看他能够审批的钱
     * @param vo
     * @return
     */
    private  Long getMaxByPlatformForFisttrial(TbSlPlatformUserWithdrawVO vo){
        double discount=CommonUtils.getdouble(vo.getDiscount());
        Long maxcount=CommonUtils.getLong(vo.getMaxAmount());
        double canloandou=discount*vo.getTotalAmount()/100;
        long canloanlong=0;
        BigDecimal canloandec=new BigDecimal(canloandou).setScale(0,BigDecimal.ROUND_HALF_UP);
        canloanlong=canloandec.longValue();
        if(canloanlong>maxcount){
            canloanlong=maxcount;
        }
        Long alsoloan=CommonUtils.getLong(vo.getTotalFirstTrialCheckAmount());
        long rateandfee=CommonUtils.getLong(vo.getTotalNotPaybackRateAndFee());
        
        TbCatchdataStrategy ca =  catchdataStrategyService.queryByPlatformUserId(vo.getId());
        
        Long lastcancredit = 0L ;
        
        if(!CommonUtils.isEmpty(ca)){
        	if(TbCatchdataStrategy.NOALSOLOAN.equals(ca.getLoanAmountType())){
        		 lastcancredit = canloanlong-rateandfee;
        	}else {
        		lastcancredit = canloanlong-alsoloan-rateandfee;
        	}
        }else {
        	    lastcancredit = canloanlong-alsoloan-rateandfee;
        }
        
        return  lastcancredit;
    }


    /**
    /**
     * 算法的基本思想：
     * 1.查询出商户的每个平台的应收账期，折扣率，已贷款额
     * 2.循环每个平台计算每个平台可贷多少钱（最大可贷额：应收账期*折扣率，max可待额）
     * 3.
     * @param amount
     * @param joinid
     * @param idofpaynow
     * @throws BusinessException
     */

    @Override
    public List<TbSlLoanCreditLog> updateForReLoan(long amount, int joinid, String idofpaynow,TbSlLoanCreditVoForFront vo,Integer bankacc) throws BusinessException {
    	String notcompleteCount = tbSlLoanCreditService.selectNotcompleteCreditLoanByJoinid(joinid); 
    	if (CommonUtils.getInt(notcompleteCount) > 0)
    		throw new BusinessException("该用户还有未完成的贷款记录，请完成后重试.");
    	
    	TbSlCreditControll controllvo=vo.getTbSlCreditControll();
       tbSlCreditCtrollService.lockById(controllvo.getId());
       dataVersionValidationService.validateVO(controllvo.getId(),"tb_sl_credit_controll",controllvo.getRowUpdateTime());
        List<TbSlLoanCreditVo> listvo=vo.getListvo();
        if(CommonUtils.isEmpty(listvo)){
           throw new BusinessException("申请贷款失败");
        }
        
        String  canloanamount=getMaxLoanAmount(joinid,ISLConstDef.MERCHANT_TYPE);
        if(amount>CommonUtils.getLong(canloanamount)){
            throw new BusinessException("您所输入的金额大于可提现额");
        }
        List<TbSlLoanCreditLog> creditLogList=autoGenerationCredit(amount, joinid, idofpaynow,ISLConstDef.MERCHANT_TYPE);
        List<Integer> list=new ArrayList<>();
        if(!CommonUtils.isEmpty(creditLogList)){
            String targetPDFFileFolder = FileUploadUtils.getDefaultBaseDir()
                    + File.separator + ISLConstDef.slLoanApplyGenFileDir;
            String[] s = slservice.generateSLLoanApplyFile(joinid, bankacc, creditLogList, 
                    targetPDFFileFolder); 
            String contractfilepath = ISLConstDef.slLoanApplyGenFileDir
                    + File.separator + FileUploadUtils.getFileNameFromPath(s[0]);
            
            //生成的融资申请书在下载表中生成记录，将记录id值放入下载字段
            TbUploadFile uploadFileVO=new TbUploadFile();
            uploadFileVO.setDownloadPath(contractfilepath);
            uploadFileVO.setOriginalName(IConstDef.DOWNLOAD_LOANAPPLY);
            uploadFileVO.setIdOfTbMerchantUser(joinid);
            uploadFileVO.setStatus(IConstDef.UPLOADSTATUS_COMMITED);
            uploadFileVO.setIdOfTbMerchantUser(joinid);
            uploadFileVO.setUploadOperator(String.valueOf(joinid));
            uploadFileVO.setFileType(ISLConstDef.SUPPLY_LOAN_APPLY_AUTOGEN);
            
            uploadFileService.insert(uploadFileVO);
            TbSlProcessInfo processInfo=new TbSlProcessInfo(); //贷款表关联流程
            processInfo.setAmount(new Long(amount).toString());
            processInfo.setUserIdOfJoinOfDebtor(joinid);
            processInfo.setUserIdOfJoinOfCreditor(creditLogList.get(0).getUserIdOfJoinOfCreditor());
            processInfo.setLoanStatus(new Integer(IConstDef.LOAN_TYPE_OF_SUBMITFILE).toString());
            processInfo.setApplyDate(creditLogList.get(0).getCreditTime());
            processInfo.setUserIdOfIPayNowOfDebtor(creditLogList.get(0).getUserIdOfIPayNowOfDebtor());
            tbSlProcessInfoService.insert(processInfo);
            Integer processinfoid=processInfo.getId();
            int i=1;
           for(TbSlLoanCreditLog logvo:creditLogList){
               logvo.setCode(s[i]);
               logvo.setMaterialDownload(uploadFileVO.getId() + "");
               logvo.setIdOfBankAcc(bankacc);
               logvo.setLastRefundTime("");  //为了兼容后台保理员填写的贷款有效到期日
               logvo.setProcessInfoId(processinfoid);
               i++;
           }
            tbSlLoanCreditService.insertBatch(creditLogList);
            for(TbSlLoanCreditLog logvo:creditLogList){
                list.add(logvo.getId());
            }

        }
        Map<String,Object> map=new HashMap<>();
        map.put("id_of_merchant",joinid);
        map.put("amount",amount);
        tbSlCreditCtrollService.update(map);
        List<TbSlLoanCreditLog> listvos=tbSlLoanCreditService.queryTsById(list);
        return listvos ;
    }

    @Override
    public List<TbSlLoanCreditLog> autoGenerationCredit(long amount, int joinid, String idofpaynow,String type) throws BusinessException {
        List<TbSlPlatformUserWithdrawVO> listByJoinuserId = tbSlPlatformUserService.selectPlatformUserWithdrawListByJoinuserId(joinid);
        if(CommonUtils.isEmpty(listByJoinuserId)){
            throw  new BusinessException("查询用户的电商平台的可提额度失败");
        }
        TbSlLoanApplication appvo=this.applicationService.queryTbSlApplicationByJoinId(joinid);
        TbMerchantUser uservo=userBaseService.queryJoinUserInfoById(appvo.getIdOfTbMerchantUserOfCreditor());
        List<TbSlLoanCreditLog> creditLogList=new ArrayList<>();
       for(TbSlPlatformUserWithdrawVO vo:listByJoinuserId){
           if(amount<=0){
               break;
           }
           Long canloan=new Long(0);
           if(ISLConstDef.MERCHANT_TYPE.equals(type)){
               canloan=getMaxByPlatform(vo);
           }else{
             canloan=getMaxByPlatformForOperator(vo);
           }

           vo.setAvailableCredit(canloan);

       }

        listByJoinuserId=tbSlPlatformUserService.sortPlatformUserWithdrawVOByAvailableCredit(listByJoinuserId);

        for(TbSlPlatformUserWithdrawVO vo:listByJoinuserId){
            if(amount<=0){
                break;
            }
            //Long canloan=getMaxByPlatform(vo);
            Long canloan=vo.getAvailableCredit();
            if(canloan<=0){
                continue;
            }
            TbSlLoanCreditLog logvo=new TbSlLoanCreditLog();
            long loanamount=0;
            if(canloan>=amount){
                loanamount=amount;
                amount=0;
            }else{
                amount=amount-canloan;
                loanamount=canloan;
            }
            logvo.setUserIdOfIPayNowOfDebtor(idofpaynow);
            logvo.setUserIdOfJoinOfDebtor(joinid);
            if(!CommonUtils.isEmpty(uservo)){
                logvo.setUserIdOfIPayNowOfCreditor(uservo.getUserIdOfIPayNow());
            }
            logvo.setAccountDelta(new Long(loanamount).toString());
            logvo.setTotalNotPaybackAmount(new Long(loanamount).toString());
            logvo.setTotalNotPaybackFee("0");
            logvo.setTotalNotPaybackFeeOld("0");
            logvo.setTotalNotPaybackRate("0");
            logvo.setTotalNotPaybackRateOld("0");
            logvo.setTotalNotPaybackPenalty("0");
            logvo.setTotalNotPaybackPenaltyOld("0");
            logvo.setTotalNotPaybackRenewedAmount("0");
            logvo.setTotalNotPaybackRenewedFee("0");
            logvo.setTotalNotPaybackRenewedFeeOld("0");
            logvo.setTotalNotPaybackRenewedRate("0");
            logvo.setTotalNotPaybackRenewedRateOld("0");
            logvo.setCreditTime(TimeUtils.getCurDate());
            logvo.setUserIdOfJoinOfCreditor(appvo.getIdOfTbMerchantUserOfCreditor());
            logvo.setCreditstatus(IConstDef.LOAN_TYPE_OF_SUBMITFILE);
            String fee=vo.getFee();
            if(CommonUtils.isEmpty(fee)){
             fee="0";
            }
            logvo.setFee(fee);
            String rate=vo.getRate();
            if(CommonUtils.isEmpty(rate)){
                rate="0";
            }
            logvo.setRate(rate);
             String penalty=appvo.getPenalty();
            if(CommonUtils.isEmpty(penalty)){
                penalty="0";
            }
            logvo.setPenalty(penalty);
            logvo.setCalculateDate(TimeUtils.getCurDate());
            logvo.setIdOfPlatform(vo.getId());
            String loanperiod=vo.getLoanPeriod();
            if(!CommonUtils.isEmpty(loanperiod)){
                String expireddate=TimeUtils.getDateAfterDays(Integer.parseInt(loanperiod));
                logvo.setLastRefundTime(expireddate);
            }
            creditLogList.add(logvo);
        }
        return creditLogList;
    }




    /**
     * 更新贷款表，更新放款方，
     * @param id
     * @param joinid
     * @param maxdays
     * @param orderid
     * @throws BusinessException
     */
    private void updateRealLoan(int id,int joinid,String maxdays,String orderid,int idOfTbFactoryingOperator,String mhtnofrom,String voucher)throws BusinessException{
        String expireddate=TimeUtils.getDateAfterDays(Integer.parseInt(maxdays));
        Map<String,Object>  parammap=new HashMap<String, Object>();
        parammap.put("id",id);
        parammap.put("creditstatus",IConstDef.LOAN_TYPE_OF_NOTPAY);
        parammap.put("realLoanTime",TimeUtils.getCurDate());
        parammap.put("lastRefundTime",expireddate);
        parammap.put("creditOrderId",orderid);
        parammap.put("idOfTbFactoryingOperator",idOfTbFactoryingOperator);
        parammap.put("userIdOfIPayNowOfCreditor",mhtnofrom);
        parammap.put("calculateDate",TimeUtils.getCurDate());
        parammap.put("voucher",voucher);
        this.tbSlLoanCreditService.updateTbSlLoanCredit(parammap);
    }

    /**
     * 贷款 还款表更新
     * @param amount
     * @param totalpayrate
     * @param totalpayfee
     * @param totalrenewrate
     * @param totalrenewfee
     * @param totalpenalty
     * @param totalrenewedamount
     * @param joinid
     * @throws BusinessException
     */

    private void repayLoanStat(TbSlLoanInfo loanInfo,long amount,long totalpayrate,long totalpayfee ,long totalrenewrate ,long totalrenewfee ,long totalpenalty ,long totalrenewedamount ,int joinid,int idofplatform)throws BusinessException{

            String totalNotPaybackAmount=loanInfo.getTotalNotPaybackAmount();
            long  totalNotPaybackAmountlong=0;
            totalNotPaybackAmountlong=Long.parseLong(totalNotPaybackAmount)-amount;
            String  totalNotPayBackRate=loanInfo.getTotalNotPaybackRate();
            long totalNotPayBackRatelong=0;
                totalNotPayBackRatelong=Long.parseLong(totalNotPayBackRate)-totalpayrate;
            long totalPayBackAmountlong=0;
             String  totalPayBackAmount=loanInfo.getTotalPayBackAmount();
             String  totalInterestRate=loanInfo.getTotalInterestRate();
            long totalInterestRatelong=0;
              totalPayBackAmountlong=Long.parseLong(totalPayBackAmount)+amount;
              totalInterestRatelong=Long.parseLong(totalInterestRate)+totalpayrate;
             //计算利率值
             long  totalNotPaybackFeeLong=0;
                String totalNotPaybackFee=loanInfo.getTotalNotPaybackFee();
                totalNotPaybackFeeLong=Long.parseLong(totalNotPaybackFee)-totalpayfee;
             long totalInterestFeeLong=0;
                String totalInterestFee=loanInfo.getTotalInterestFee();
                totalInterestFeeLong=Long.parseLong(totalInterestFee)+totalpayfee;
             //计算罚息值
              long totalInterestPenaltyLong=0;
                String totalInterestPenalty=loanInfo.getTotalInterestPenalty();
                totalInterestPenaltyLong=Long.parseLong(totalInterestPenalty)+totalpenalty;
             long totalNotPaybackPenaltyLong=0;
                String totalNotPaybackPenalty=loanInfo.getTotalNotPaybackPenalty();
                totalNotPaybackPenaltyLong=Long.parseLong(totalNotPaybackPenalty)- totalpenalty;
              //计算展息利率值
              long totalNotPaybackRenewedFeeLong=0;
                String totalNotPaybackRenewedFee=loanInfo.getTotalNotPaybackRenewedFee();
                totalNotPaybackRenewedFeeLong=Long.parseLong(totalNotPaybackRenewedFee)-totalrenewfee;
              long totalInterestRenewedFeeLong=0;
                String totalInterestRenewedFee=loanInfo.getTotalInterestRenewedFee();
                totalInterestRenewedFeeLong=Long.parseLong(totalInterestRenewedFee)+totalrenewfee;
              //计算展息手续费制
              long totalNotPaybackRenewedRateLong=0;
                String totalNotPaybackRenewedRate=loanInfo.getTotalNotPaybackRenewedRate();
                totalNotPaybackRenewedRateLong=Long.parseLong(totalNotPaybackRenewedRate)-totalrenewrate;
                long totalInterestRenewedRateLong=0;
                String totalInterestRenewedRate=loanInfo.getTotalInterestRenewedRate();
                totalInterestRenewedRateLong=Long.parseLong(totalInterestRenewedRate)+totalrenewrate;
                //计算展息一次性手续费
              long totalPaybackRenewedAmountLong=0;
                String totalPaybackRenewedAmount=loanInfo.getTotalPaybackRenewedAmount();
                totalPaybackRenewedAmountLong=Long.parseLong(totalPaybackRenewedAmount)+totalrenewedamount;
              long totalNotPaybackRenewedAmountLong=0;
                String totalNotPaybackRenewedAmount=loanInfo.getTotalNotPaybackRenewedAmount();
                totalNotPaybackRenewedAmountLong=Long.parseLong(totalNotPaybackRenewedAmount)-totalrenewedamount;

            Map<String ,Object> paramap=new HashMap<String, Object>();
            paramap.put("id",loanInfo.getId());
                loanInfo.setTotalNotPaybackRate(new Long(totalNotPayBackRatelong).toString());
                loanInfo.setTotalNotPaybackAmount(new Long(totalNotPaybackAmountlong).toString());
                loanInfo.setTotalPayBackAmount(new Long(totalPayBackAmountlong).toString() );
                loanInfo.setTotalInterestRate(new Long(totalInterestRatelong).toString());
                loanInfo.setTotalNotPaybackFee(new Long(totalNotPaybackFeeLong).toString());
                loanInfo.setTotalInterestFee(new Long(totalInterestFeeLong).toString()) ;
                loanInfo.setTotalNotPaybackRenewedFee(new Long(totalNotPaybackRenewedFeeLong).toString());
                loanInfo.setTotalInterestRenewedFee(new Long(totalInterestRenewedFeeLong).toString()) ;
                loanInfo.setTotalNotPaybackRenewedRate(new Long(totalNotPaybackRenewedRateLong).toString());
                loanInfo.setTotalInterestRenewedRate(new Long(totalInterestRenewedRateLong).toString());
                loanInfo.setTotalPaybackRenewedAmount(new Long(totalPaybackRenewedAmountLong).toString());
                loanInfo.setTotalNotPaybackRenewedAmount(new Long(totalNotPaybackRenewedAmountLong).toString()) ;
                loanInfo.setTotalInterestPenalty (new Long(totalInterestPenaltyLong).toString());
                loanInfo.setTotalNotPaybackPenalty(new Long(totalNotPaybackPenaltyLong).toString());
        }





    private void updateLoanLog(TbSlLoanInfo loaninfo)throws BusinessException{
        loanInfoService.lockId(loaninfo.getId());
        dataVersionValidationService.validateVO(loaninfo.getId(),loaninfo.getTableName(),loaninfo.getRowUpdateTime());
        loanInfoService.updateById(loaninfo);
        TbSlLoanInfoLog logvo=new TbSlLoanInfoLog();
        long totalInterestRate=CommonUtils.getLong(loaninfo.getTotalInterestRate())+CommonUtils.getLong(loaninfo.getTotalInterestFee())+
                CommonUtils.getLong(loaninfo.getTotalInterestRenewedFee())+CommonUtils.getLong(loaninfo.getTotalInterestRenewedRate())
                //+CommonUtils.getLong(loaninfo.getTotalPaybackRenewedAmount())
                +CommonUtils.getLong(loaninfo.getTotalInterestPenalty());
        long totalnotbackrate=CommonUtils.getLong(loaninfo.getTotalNotPaybackRate())+CommonUtils.getLong(loaninfo.getTotalNotPaybackFee())+
                CommonUtils.getLong(loaninfo.getTotalNotPaybackPenalty())+
                CommonUtils.getLong(loaninfo.getTotalNotPaybackRenewedFee())+CommonUtils.getLong(loaninfo.getTotalNotPaybackRenewedRate());
       if(!CommonUtils.isEmpty(loaninfo)){
           logvo.setIdOfTbMerchantUser(loaninfo.getIdOfTbMerchantUser());
           logvo.setCurdate(TimeUtils.getCurDate());
           logvo.setTotalInterestRate(new Long(totalInterestRate).toString());
           logvo.setTotalPayBackAmount(loaninfo.getTotalPayBackAmount());
           logvo.setTotalNotPaybackAmount(loaninfo.getTotalNotPaybackAmount());
           logvo.setTotalLoanAmount(loaninfo.getTotalLoanAmount());
           logvo.setTotalNotPaybackRate(new Long(totalnotbackrate).toString());
           logvo.setTotalNotPaybackRenewedAmount(loaninfo.getTotalNotPaybackRenewedAmount());
           logvo.setTotalPaybackRenewedAmount(loaninfo.getTotalPaybackRenewedAmount());
           tbSLLoanInfoLogService.insertTbSlLoanInfo(logvo);
       } else{
            throw new BusinessException("新增贷款统计日志表出错");
       }


    }

    /**
     * 貸款更新贷款的总表
     */
    private void updateLoanStat(long amount,int joinid,Integer idofLoanInfo,String tsofloaninfo)throws BusinessException{
        TbSlLoanInfo loanInfo=null;
        if(!CommonUtils.isEmpty(idofLoanInfo)){
             loanInfoService.lockId(idofLoanInfo);
            dataVersionValidationService.validateVO(idofLoanInfo,"tb_sl_loan_info",tsofloaninfo);
            loanInfo=loanInfoService.queryById(idofLoanInfo);
            if(CommonUtils.isEmpty(loanInfo)){
                throw new BusinessException("根据pk查询贷款总表为空，请校验数据");
            }
        }
        if(loanInfo!=null){
        String  totalLoanAmount=loanInfo.getTotalLoanAmount();
        long  totalLoanAmountlong=0;
        if(!StringUtils.isEmpty(totalLoanAmount)){
            totalLoanAmountlong=totalLoanAmountlong+Long.parseLong(totalLoanAmount)+amount;
        } else{
            totalLoanAmountlong=amount;
        }
        String totalNotPaybackAmount=loanInfo.getTotalNotPaybackAmount();
            long  totalNotPaybackAmountlong=0;
         if(!StringUtils.isEmpty(totalNotPaybackAmount)){
             totalNotPaybackAmountlong=totalNotPaybackAmountlong+Long.parseLong(totalNotPaybackAmount)+amount;
         }else{
             totalNotPaybackAmountlong=amount;
         }
        Map<String ,Object> paramap=new HashMap<String, Object>();
         paramap.put("id",loanInfo.getId());
         paramap.put("totalLoanAmount",new Long(totalLoanAmountlong).toString());
         paramap.put("totalNotPaybackAmount",new Long(totalNotPaybackAmountlong).toString());
         this.loanInfoService.updateTbSlLoanInfo(paramap);
          long totalInterestRate=CommonUtils.getLong(loanInfo.getTotalInterestRate())+CommonUtils.getLong(loanInfo.getTotalInterestFee())+
                  CommonUtils.getLong(loanInfo.getTotalInterestRenewedFee())+CommonUtils.getLong(loanInfo.getTotalInterestRenewedRate())
//                  +CommonUtils.getLong(loanInfo.getTotalPaybackRenewedAmount())
                  +CommonUtils.getLong(loanInfo.getTotalInterestPenalty());
            TbSlLoanInfoLog log=new TbSlLoanInfoLog();
          long totalnotbackrate=CommonUtils.getLong(loanInfo.getTotalNotPaybackRate())+CommonUtils.getLong(loanInfo.getTotalNotPaybackFee())+
                  CommonUtils.getLong(loanInfo.getTotalNotPaybackPenalty())+
                  CommonUtils.getLong(loanInfo.getTotalNotPaybackRenewedFee())+CommonUtils.getLong(loanInfo.getTotalNotPaybackRenewedRate());
            log.setTotalLoanAmount(new Long(totalLoanAmountlong).toString());
            log.setTotalInterestRate(new Long(totalInterestRate).toString());
            log.setTotalNotPaybackAmount(new Long(totalNotPaybackAmountlong).toString());
            log.setTotalNotPaybackRate(new Long(totalnotbackrate).toString());
            log.setTotalPayBackAmount(loanInfo.getTotalPayBackAmount());
            log.setIdOfTbMerchantUser(joinid);
            log.setCurdate(TimeUtils.getCurDate());
            log.setTotalNotPaybackRenewedAmount(loanInfo.getTotalNotPaybackRenewedAmount());
            log.setTotalPaybackRenewedAmount(loanInfo.getTotalPaybackRenewedAmount());
            this.tbSLLoanInfoLogService.insertTbSlLoanInfo(log);
        }
        else{
            TbSlLoanInfo info=new TbSlLoanInfo();
            info.setIdOfTbMerchantUser(joinid);
            info.setTotalLoanAmount(new Long(amount).toString());
            info.setTotalNotPaybackRate("0");
            info.setTotalPayBackAmount("0");
            info.setTotalNotPaybackAmount(new Long(amount).toString());
            info.setTotalInterestRate("0");
            info.setTotalNotPaybackFee("0");
            info.setTotalInterestFee("0");
            info.setTotalNotPaybackRenewedRate("0");
            info.setTotalInterestRenewedRate("0");
            info.setTotalNotPaybackRenewedFee("0");
            info.setTotalInterestRenewedFee("0");
            info.setTotalNotPaybackPenalty("0");
            info.setTotalInterestPenalty("0");
            info.setTotalNotPaybackRenewedAmount("0");
            info.setTotalPaybackRenewedAmount("0");
            this.loanInfoService.insert(info);
            TbSlLoanInfoLog log=new TbSlLoanInfoLog();
            log.setTotalLoanAmount(new Long(amount).toString());
            log.setTotalInterestRate("0");
            log.setTotalNotPaybackAmount(new Long(amount).toString());
            log.setTotalNotPaybackRate("0");
            log.setTotalPayBackAmount("0");
            log.setIdOfTbMerchantUser(joinid);
            log.setCurdate(TimeUtils.getCurDate());
            log.setTotalNotPaybackRenewedAmount("0");
            log.setTotalPaybackRenewedAmount("0");
            this.tbSLLoanInfoLogService.insertTbSlLoanInfo(log);
        }

    }



    @Override
    public void execAutomaticRepayLoan(String type) throws BusinessException {

        List<TbSlFinanceinfoVO> slFinanceinfoList=financeinfoService.queryAllUserUnsuccessRefundTask();
         if(CommonUtils.isEmpty(slFinanceinfoList)){
             return;
         }
        for(TbSlFinanceinfoVO finaccount:slFinanceinfoList){
        	//天津方鑫商户不做自动还款，直接跳过
        	if (123 ==finaccount.getIdOfTbMerchantUser())
        		continue;
        	
            try{
            long amountlong = accountbaseservice.queryFinanceAccountBanlance(finaccount.getMhtno());
            if(amountlong>0){
	            ((TbSlLoanService) AopContext.currentProxy()).updateForRepayLoanByJoinid(amountlong, finaccount.getIdOfTbMerchantUser(), finaccount.getMhtno(),type);
	                financeinfoService.updateSLFinalceStatusAndMemoById(finaccount.getId(),ISLConstDef.SLREFUND_RUNSUCESS, "运行成功");
	            if(!CommonUtils.isDev()){
	            	BigDecimal amountdecimal=new BigDecimal(amountlong);
	            	sendMsg(new String[]{"%refunddate%", "%money%"}, new String[]{TimeUtils.getCurDate(), amountdecimal.divide(new BigDecimal(100)).doubleValue() + ""}, ISLConstDef.AUTO_REFUND, finaccount.getMobile());
                    //发送提醒邮件
                    StringBuffer str = new StringBuffer();
                    str.append("mhtNoFrom：" + finaccount.getIdOfTbMerchantUser() + "<br/>");
                    str.append("amount：" + amountdecimal.divide(new BigDecimal(100)).doubleValue()  + "<br/>");
                    str.append("memo：" + "供应链自动还款，请及时提现");
                    EmailSendUtil.send("guoting@18join.com;hgc@18join.com", "请关注：供应链自动提现", str.toString());

                }
            }
               }catch (Exception e){
                if(e instanceof  BusinessException){
                    financeinfoService.updateSLFinalceStatusAndMemoById(finaccount.getId(),ISLConstDef.SLREFUND_RUNFAILED, e.getMessage());
                }else{
                financeinfoService.updateSLFinalceStatusAndMemoById(finaccount.getId(),ISLConstDef.SLREFUND_RUNFAILED, e.toString());
                }
                continue;
            }
        }
    }


    @Override
    public void updateForAutoRepayLoanByJoinid(long amount, int joinid, String idofpaynow,String pwd,TbSlRefundForFrontVo vo) throws BusinessException {
        boolean isfrezz=merchantuserExceptionorderBaseService.isFreezeByJoinuserID(joinid);
        if(isfrezz){
            throw new BusinessException("账户状态为锁定，请联系保理公司");
        }

        if(isDaySpecial()){
            throw new BusinessException("节假日期间不能还款");
        }
        if(!CommonUtils.expireTime()){
            throw new BusinessException("请于当日下午15:00前还款");
        }
        if(amount==0){
            return;
        }
        long loanamount=tbSlLoanInfoService.queryTotalNotPayback(joinid);
        if(loanamount>10000&&amount<10000){
            throw new BusinessException("还款金额不能低于100元");
        }
        if(loanamount<=10000&&loanamount!=amount){
             throw new BusinessException("请全部还清贷款额");
        }
        List<TbSlRefundVo> tbSlRefundVolist=vo.getTbSlRefundVoList();

        if(CommonUtils.isEmpty(tbSlRefundVolist)){
            String orderid=UUIDUtils.create();
            this.accountbaseservice.rechargeAccountBalance(idofpaynow,IConstDef.ACCTYPE_BASE,pwd,idofpaynow,IConstDef.ACCTYPE_BASE,new Long(amount).toString(),"还款",orderid);
            return;
        }

        TbSlLoanApplication appvo=applicationService.queryTbSlApplicationByJoinId(joinid);
        if(appvo==null){
            throw new BusinessException("查询商户的供应链贷申请记录报错，请联系保理公司");
        }
        String UserIdOfIPayNowOfCreditor=userBaseService.queryPayUserByJoinUserID(appvo.getIdOfTbMerchantUserOfCreditor());
        long nowamount=amount;
        String orderid=UUIDUtils.create();
        List<TbSlLoanCreditLogForFront> list=new ArrayList<>();
        for(TbSlRefundVo refundVo:tbSlRefundVolist) {
            list.add(refundVo.getCreditVo());
        }
        TbSlLoanInfo loanInfo=vo.getTbSlLoanInfo();
        for(TbSlLoanCreditLogForFront tbSlLoanCreditLogForFront:list){
            tbSlLoanCreditService.lockById(tbSlLoanCreditLogForFront.getId());
            dataVersionValidationService.validateVO(tbSlLoanCreditLogForFront.getId(),"tb_sl_loan_credit_log",tbSlLoanCreditLogForFront.getRowUpdateTime());
            TbSlLoanCreditLog creditLog=tbSlLoanCreditService.queryCreditLogById(tbSlLoanCreditLogForFront.getId());
            if(creditLog.getCalculateDate()!=null&&!creditLog.getCalculateDate().equals(TimeUtils.getCurDate())){
                throw  new BusinessException("计息时间不是当天,暂时不能还款，请联系保理公司");
            }
            if(nowamount<=0){
                break;
            }
           nowamount= updateRepayOneByOneLoan(creditLog, appvo, nowamount, joinid, orderid,loanInfo,null,null);
            }
          updateLoanLog(loanInfo);
        try{
        List rechargelist= this.accountbaseservice.rechargeAccountBalance(idofpaynow,IConstDef.ACCTYPE_BASE,pwd,UserIdOfIPayNowOfCreditor,IConstDef.ACCTYPE_BASE,new Long(amount-nowamount).toString(),"还款",orderid);

        }catch (Exception e){
            if(e instanceof IPayNowException){
                TbRedo redo=new TbRedo();
                redo.setApplyDate(TimeUtils.getCurDate());
                redo.setOrderId(orderid);
                Map<String,Object> map=new HashMap<>();
                map.put("amount",amount);
                map.put("joinid",joinid);
                map.put("vo",vo);
                byte[] bytes=CommonUtils.serialize(map);
                redo.setBusinessType(IConstDef.REPAY);
                redo.setParamstr(bytes);
                redo.setIsdo(IConstDef.UNDO);
                tbRedoService.insertTbRedo(redo);
                TbMerchantuserExceptionorder ordervo=new TbMerchantuserExceptionorder();
                ordervo.setOrderid(orderid);
                ordervo.setAccountStatus(IConstDef.ACCOUNT_STATUS_FREEZE);
                ordervo.setIdOfTbMerchantUser(joinid);
                ordervo.setBusinessType(IConstDef.EXCEPTIONORDER_TYPE_RECHARGE);
                ordervo.setOrderTime(TimeUtils.getCurDateTime());
                merchantuserExceptionorderBaseService.insertMerchantuserExceptionorder(ordervo);

            }
            throw e;
        }
        orderid=UUIDUtils.create();
        if(nowamount>0){
            try{
          List rechargelist= this.accountbaseservice.rechargeAccountBalance(idofpaynow,IConstDef.ACCTYPE_BASE,pwd,idofpaynow,IConstDef.ACCTYPE_BASE,new Long(nowamount).toString(),"回款",orderid);
            }catch (Exception e){

            }
        }

    }

    @Override
    public void updateForRedoAutoRepayLoanByJoinid(long amount, int joinid, TbSlRefundForFrontVo vo,String orderId,String applydate) throws BusinessException {
        if(isDaySpecial()){
            throw new BusinessException("节假日期间不能还款");
        }
        if(!CommonUtils.expireTime()){
            throw new BusinessException("请于当日下午15:00前还款");
        }
        if(amount==0){
            return;
        }
        long loanamount=tbSlLoanInfoService.queryTotalNotPayback(joinid);
        if(loanamount>10000&&amount<10000){
            throw new BusinessException("还款金额不能低于100元");
        }
        if(loanamount<=10000&&loanamount!=amount){
             throw new BusinessException("请全部还清贷款额");
        }
        List<TbSlRefundVo> tbSlRefundVolist=vo.getTbSlRefundVoList();

        if(CommonUtils.isEmpty(tbSlRefundVolist)){
            String orderid=UUIDUtils.create();
            return;
        }

        TbSlLoanApplication appvo=applicationService.queryTbSlApplicationByJoinId(joinid);
        if(appvo==null){
            throw new BusinessException("查询商户的供应链贷申请记录报错，请联系保理公司");
        }
        String UserIdOfIPayNowOfCreditor=userBaseService.queryPayUserByJoinUserID(appvo.getIdOfTbMerchantUserOfCreditor());
        long nowamount=amount;
        List<TbSlLoanCreditLogForFront> list=new ArrayList<>();
        for(TbSlRefundVo refundVo:tbSlRefundVolist) {
            list.add(refundVo.getCreditVo());
        }
        TbSlLoanInfo loanInfo=vo.getTbSlLoanInfo();
        for(TbSlLoanCreditLogForFront tbSlLoanCreditLogForFront:list){
            tbSlLoanCreditService.lockById(tbSlLoanCreditLogForFront.getId());
            dataVersionValidationService.validateVO(tbSlLoanCreditLogForFront.getId(),"tb_sl_loan_credit_log",tbSlLoanCreditLogForFront.getRowUpdateTime());
            TbSlLoanCreditLog creditLog=tbSlLoanCreditService.queryCreditLogById(tbSlLoanCreditLogForFront.getId());
            if(creditLog.getCalculateDate()!=null&&!creditLog.getCalculateDate().equals(TimeUtils.getCurDate())){
                throw  new BusinessException("计息时间不是当天,暂时不能还款，请联系保理公司");
            }
            if(nowamount<=0){
                break;
            }
            nowamount= updateRepayOneByOneLoan(creditLog, appvo, nowamount, joinid, orderId,loanInfo,null,applydate);
        }
        updateLoanLog(loanInfo);

        transferTokenStatusService.updateTransferTokenStatus(orderId,IConstDef.TRANSFERSTATUS_SUCCESS,"处理成功");
        tbRedoService.updateTbRedo(orderId);
        TbMerchantuserExceptionorder ordervo=new TbMerchantuserExceptionorder();
        ordervo.setHandleTime(TimeUtils.getCurDateTime());
        ordervo.setHandleMemo("处理完毕");
        ordervo.setOrderid(orderId);
        ordervo.setAccountStatus(IConstDef.ACCOUNT_STATUS_UNFREEZE);
        merchantuserExceptionorderBaseService.updateVOByOrderId(ordervo);
    }



    @Override
    public void updateForAutoRepayForOperator(long amount, int joinid, String idofpaynow, String ventor, TbSlRefundForFrontVo vo) throws BusinessException {
        if(isDaySpecial()){
            throw new BusinessException("节假日期间不能还款");
        }
//        if(!CommonUtils.expireTime()){
//            throw new BusinessException("请于当日下午15:00前还款");
//        }
        if(amount==0){
            return;
        }
        long loanamount=tbSlLoanInfoService.queryTotalNotPayback(joinid);
        if(loanamount>=10000&&amount<10000){
            throw new BusinessException("还款额不能低于100元");
        }
        if(loanamount<10000&&loanamount>amount){
            throw new BusinessException("欠款额必须全部还清");
        }
        List<TbSlRefundVo> tbSlRefundVolist=vo.getTbSlRefundVoList();

        if(CommonUtils.isEmpty(tbSlRefundVolist)){
            return;
        }

        TbSlLoanApplication appvo=applicationService.queryTbSlApplicationByJoinId(joinid);
        if(appvo==null){
            throw new BusinessException("查询商户的供应链贷申请记录报错，请联系保理公司");
        }
        String UserIdOfIPayNowOfCreditor=userBaseService.queryPayUserByJoinUserID(appvo.getIdOfTbMerchantUserOfCreditor());
        long nowamount=amount;
        String orderid=UUIDUtils.create();
        List<TbSlLoanCreditLogForFront> list=new ArrayList<>();
        for(TbSlRefundVo refundVo:tbSlRefundVolist) {
            list.add(refundVo.getCreditVo());
        }
        TbSlLoanInfo loanInfo=vo.getTbSlLoanInfo();
        for(TbSlLoanCreditLogForFront tbSlLoanCreditLogForFront:list){
            tbSlLoanCreditService.lockById(tbSlLoanCreditLogForFront.getId());
            dataVersionValidationService.validateVO(tbSlLoanCreditLogForFront.getId(),"tb_sl_loan_credit_log",tbSlLoanCreditLogForFront.getRowUpdateTime());
            TbSlLoanCreditLog creditLog=tbSlLoanCreditService.queryCreditLogById(tbSlLoanCreditLogForFront.getId());
            if(creditLog.getCalculateDate()!=null&&!creditLog.getCalculateDate().equals(TimeUtils.getCurDate())){
                throw  new BusinessException("计息时间不是当天,暂时不能还款，请联系保理公司");
            }
            if(nowamount<=0){
                break;
            }
            nowamount= updateRepayOneByOneLoan(creditLog, appvo, nowamount, joinid, orderid,loanInfo,ventor,null);
        }

        updateLoanLog(loanInfo);
        uploadFileService.updateStatusById(CommonUtils.getInt(ventor),IConstDef.UPLOADSTATUS_COMMITED);

    }

    @Override
    public void updateForRepayLoanByJoinid(long amount, int joinid, String idofpaynow,String type) throws BusinessException {
        if(isDaySpecial()){
            throw new BusinessException("节假日期间不能还款");
        }
        //自动回款一般三点不入账，如果入账的话肯定是三点之前充值的
//        if(!CommonUtils.expireTime()){
//            throw new BusinessException("请于当日下午15:00前还款");
//        }
        if(amount==0){
            return;
        }
        long loanamount=tbSlLoanInfoService.queryTotalNotPayback(joinid);
        if(ISLConstDef.AUTO_OPERATOR.equals(type)){
        if(loanamount>=10000&&amount<10000){
            throw new BusinessException("最小还款金额不能低于100元");
        }
        if(loanamount<10000&&amount<loanamount){
            throw new BusinessException("请全部还清欠款额");
        }
        }
        List<TbSlLoanCreditLog> list=tbSlLoanCreditService.queryNotPayBackCreditLogByJoinidNotPage(joinid);
        if(CommonUtils.isEmpty(list)){
            String orderid=UUIDUtils.create();
            this.accountbaseservice.rechargeAccountBalanceNoPwd(idofpaynow,IConstDef.ACCTYPE_FINANCING,idofpaynow,IConstDef.ACCTYPE_BASE,new Long(amount).toString(),"回款",orderid);
            return;
        }
        TbSlLoanApplication appvo=applicationService.queryTbSlApplicationByJoinId(joinid);
        if(appvo==null){
            throw new BusinessException("查询商户的供应链贷申请记录报错，请联系保理公司");
        }
        String UserIdOfIPayNowOfCreditor=userBaseService.queryPayUserByJoinUserID(appvo.getIdOfTbMerchantUserOfCreditor());
        long nowamount=amount;
        String orderid=UUIDUtils.create();
        TbSlLoanInfo loanInfo= loanInfoService.queryTbSlLoanInfoByJoinid(joinid);
        loanInfoService.lockId(loanInfo.getId());
        for(TbSlLoanCreditLog creditLog:list){
            if(creditLog.getCalculateDate()!=null&&!creditLog.getCalculateDate().equals(TimeUtils.getCurDate())){
                throw  new BusinessException("计息时间不是当天,暂时不能还款，请联系保理公司");
            }
            if(nowamount>0){
                nowamount= updateRepayOneByOneLoan(creditLog, appvo, nowamount, joinid, orderid,loanInfo,null,null);
            }else{
                break;
            }
        }
        updateLoanLog(loanInfo);
        if((amount-nowamount)>0){
       try{
        List rechargelist= this.accountbaseservice.rechargeAccountBalanceNoPwd(idofpaynow,IConstDef.ACCTYPE_FINANCING,UserIdOfIPayNowOfCreditor,IConstDef.ACCTYPE_BASE,new Long(amount-nowamount).toString(),"还款",orderid);
       }catch (Exception e){
           if(e instanceof IPayNowException){
               TbRedo redo=new TbRedo();
               redo.setApplyDate(TimeUtils.getCurDate());
               redo.setOrderId(orderid);
               Map<String,Object> map=new HashMap<>();
               map.put("amount",amount);
               map.put("joinid",joinid);
               byte[] bytes=CommonUtils.serialize(map);
               redo.setBusinessType(IConstDef.AUTOREPAY);
               redo.setParamstr(bytes);
               tbRedoService.insertTbRedo(redo);
               TbMerchantuserExceptionorder ordervo=new TbMerchantuserExceptionorder();
               ordervo.setOrderid(orderid);
               ordervo.setAccountStatus(IConstDef.ACCOUNT_STATUS_FREEZE);
               ordervo.setIdOfTbMerchantUser(joinid);
               ordervo.setBusinessType(IConstDef.EXCEPTIONORDER_TYPE_RECHARGE);
               ordervo.setOrderTime(TimeUtils.getCurDateTime());
               merchantuserExceptionorderBaseService.insertMerchantuserExceptionorder(ordervo);

           }
           throw  e;
       }
        }

        String orderid1=UUIDUtils.create();
        if(nowamount>0){
           try{  //不影响业务数据的清除。商户自己的转账即使失败了，也不能影响整个业务数据的清除
            List huikuanlist= this.accountbaseservice.rechargeAccountBalanceNoPwd(idofpaynow,IConstDef.ACCTYPE_FINANCING,idofpaynow,IConstDef.ACCTYPE_BASE,new Long(nowamount).toString(),"回款",orderid1);
           }catch (Exception e){

           }

        }
    }

    @Override
    public void updateForRedoRepayLoanByJoinid(long amount, int joinid, String applydate, String orderid) throws BusinessException {
        if(isDaySpecial()){
            throw new BusinessException("节假日期间不能还款");
        }
        if(amount==0){
            return;
        }
        long loanamount=tbSlLoanInfoService.queryTotalNotPayback(joinid);
        List<TbSlLoanCreditLog> list=tbSlLoanCreditService.queryNotPayBackCreditLogByJoinidNotPage(joinid);
        if(CommonUtils.isEmpty(list)){
            return;
        }
        TbSlLoanApplication appvo=applicationService.queryTbSlApplicationByJoinId(joinid);
        if(appvo==null){
            throw new BusinessException("查询商户的供应链贷申请记录报错，请联系保理公司");
        }
        String UserIdOfIPayNowOfCreditor=userBaseService.queryPayUserByJoinUserID(appvo.getIdOfTbMerchantUserOfCreditor());
        long nowamount=amount;
        TbSlLoanInfo loanInfo= loanInfoService.queryTbSlLoanInfoByJoinid(joinid);
        loanInfoService.lockId(loanInfo.getId());
        for(TbSlLoanCreditLog creditLog:list){
            if(creditLog.getCalculateDate()!=null&&!creditLog.getCalculateDate().equals(TimeUtils.getCurDate())){
                throw  new BusinessException("计息时间不是当天,暂时不能还款，请联系保理公司");
            }
            if(nowamount>0){
                nowamount= updateRepayOneByOneLoan(creditLog, appvo, nowamount, joinid, orderid,loanInfo,null,applydate);
            }else{
                break;
            }
        }
        updateLoanLog(loanInfo);

        transferTokenStatusService.updateTransferTokenStatus(orderid, IConstDef.TRANSFERSTATUS_SUCCESS, "处理成功");
        tbRedoService.updateTbRedo(orderid);
        TbMerchantuserExceptionorder ordervo=new TbMerchantuserExceptionorder();
        ordervo.setHandleTime(TimeUtils.getCurDateTime());
        ordervo.setHandleMemo("处理完毕");
        ordervo.setOrderid(orderid);
        ordervo.setAccountStatus(IConstDef.ACCOUNT_STATUS_FREEZE);
        merchantuserExceptionorderBaseService.updateVOByOrderId(ordervo);
    }

    @Override
    public TbSlRefundForFrontVo autoGenerationRefund(long amount, int joinid, String idofpaynow,String type) throws BusinessException {
        boolean isfrezz=merchantuserExceptionorderBaseService.isFreezeByJoinuserID(joinid);
        if(isfrezz){
            throw new BusinessException("账户状态为锁定，请联系保理公司");
        }

        if(isDaySpecial()){
            throw new BusinessException("节假日期间不能还款");
        }
        if(!CommonUtils.expireTime()&&type.equals("mch")){
            throw new BusinessException("请于当日下午15:00前还款");
        }
        List<TbSlRefundVo> list=new ArrayList<>();
        TbSlRefundForFrontVo vo=new TbSlRefundForFrontVo();
        if(amount==0){
            return vo;
        }
        long loanamount=tbSlLoanInfoService.queryTotalNotPayback(joinid);
        if(loanamount>10000&&amount<10000){
            throw new BusinessException("还款金额不能低于100元");
        }
        if(loanamount<=10000&&loanamount>amount){
            throw new BusinessException("请全部还清贷款额");
        }
        List<TbSlLoanCreditLog> creditlist=tbSlLoanCreditService.queryNotPayBackCreditLogByJoinidNotPage(joinid);
        if(CommonUtils.isEmpty(creditlist)){
            return vo;
        }
        TbSlLoanApplication appvo=applicationService.queryTbSlApplicationByJoinId(joinid);
        if(appvo==null){
            throw new BusinessException("查询商户的供应链贷申请记录报错，请联系保理公司");
        }
        TbSlLoanInfo info=loanInfoService.queryTbSlLoanInfoByJoinid(joinid);
        if(info==null){
            throw  new BusinessException("查询商户的代表记录有误，请联系保理公司");
        }
        for(TbSlLoanCreditLog creditLog:creditlist){
            if(creditLog.getCalculateDate()!=null&&!creditLog.getCalculateDate().equals(TimeUtils.getCurDate())){
                throw  new BusinessException("计息时间不是当天,暂时不能还款，请联系保理公司");
            }
            if(amount>0){
                amount=generateRefund(info,creditLog, appvo, amount, joinid,list);
            }else{
                break;
            }
        }
        vo.setTbSlLoanInfo(info);
        vo.setTbSlRefundVoList(list);
        return vo;


    }

    @Override
    public TbSlLoanCreditVoForFront queryPreLoan(long amount, int joinid, String idofpaynow,String type) throws BusinessException {
        String canloanamount=getMaxLoanAmount(joinid,type);
        if(amount>CommonUtils.getLong(canloanamount)){
            throw new BusinessException("您所输入的金额大于可提现额");
        }
        List<TbSlPlatformUserWithdrawVO> listByJoinuserId = tbSlPlatformUserService.selectPlatformUserWithdrawListByJoinuserId(joinid);
        if(CommonUtils.isEmpty(listByJoinuserId)){
            throw  new BusinessException("没有查询到该商户今日应收账款");
        }
       // TbSlLoanApplication appvo=this.applicationService.queryTbSlApplicationByJoinId(joinid);
        TbSlLoanInfo info=this.loanInfoService.queryTbSlLoanInfoByJoinid(joinid);
        List<TbSlLoanCreditVo> creditLogList=new ArrayList<>();
        for(TbSlPlatformUserWithdrawVO vo:listByJoinuserId){
            if(amount<=0){
                break;
            }
            Long canloan=new Long(0);
            if(ISLConstDef.MERCHANT_TYPE.equals(type)){
                canloan=getMaxByPlatform(vo);
            }else{
                canloan=getMaxByPlatformForOperator(vo);
            }
            vo.setAvailableCredit(canloan);

        }
        listByJoinuserId=tbSlPlatformUserService.sortPlatformUserWithdrawVOByAvailableCredit(listByJoinuserId);
        for(TbSlPlatformUserWithdrawVO vo:listByJoinuserId){
            if(amount<=0){
                break;
            }
           // Long canloan=getMaxByPlatform(vo);
            Long canloan=vo.getAvailableCredit();
            if(canloan<=0){
                continue;
            }
            TbSlLoanCreditVo logvo=new TbSlLoanCreditVo();
            long loanamount=0;
            if(canloan>=amount){
                loanamount=amount;
                amount=0;
            }else{
                amount=amount-canloan;
                loanamount=canloan;
            }
            BigDecimal rate=new BigDecimal("0");
            if(!CommonUtils.isEmpty(vo.getFee())){
               rate= rate.add(new BigDecimal(vo.getFee()));
            }
            if(!CommonUtils.isEmpty(vo.getRate())){
                rate=rate.add(new BigDecimal(vo.getRate()));
            }
            logvo.setPlatform(vo.getPlatformCnname());
            logvo.setAmount(new Long(canloan).toString());
            logvo.setPresentAmount(new Long(loanamount).toString());
            logvo.setRate(rate.toString());
            logvo.setSurplusAmount(new Long(canloan-loanamount).toString());
            creditLogList.add(logvo);
        }
        TbSlLoanCreditVoForFront vo=new TbSlLoanCreditVoForFront();
        vo.setListvo(creditLogList);
        List<TbSlLoanCreditLogForFront> tbSlLoanCreditLogForFrontList=tbSlLoanCreditService.queryTbSlLoanCreditLogForFront(joinid);
        TbSlCreditControll controllVo=tbSlCreditCtrollService.queryTbSlCreditControll(joinid);
        if(CommonUtils.isEmpty(controllVo)){
            throw new BusinessException("初始化提款版本数据有误，请联系北京九盈科技有限公司");
        }
        vo.setTbSlCreditControll(controllVo);
        if(!CommonUtils.isEmpty(info)){
        vo.setIdofloaninfo(info.getId());
        vo.setRowUpdateTime(info.getRowUpdateTime());
        }
        return vo;



    }

    @Override
    public List<TbSlPlatformUserWithdrawVO> queryPlatformDetail(int joinid) throws BusinessException {
        List<TbSlPlatformUserWithdrawVO> listByJoinuserId = tbSlPlatformUserService.selectPlatformUserWithdrawListByJoinuserId(joinid);
        if(!CommonUtils.isEmpty(listByJoinuserId)){
            for(TbSlPlatformUserWithdrawVO vo:listByJoinuserId){
                long amount=getMaxByPlatform(vo);
                vo.setAvailableCredit(amount);
            }
        }
        return listByJoinuserId;  //To change body of implemented methods use File | Settings | File Templates.
    }

    @Override
    public List<TbSlPlatformUserWithdrawVO> queryPlatformDetailForOperator(int joinid) throws BusinessException {
        List<TbSlPlatformUserWithdrawVO> listByJoinuserId = tbSlPlatformUserService.selectPlatformUserWithdrawListByJoinuserId(joinid);
        if(!CommonUtils.isEmpty(listByJoinuserId)){
            for(TbSlPlatformUserWithdrawVO vo:listByJoinuserId){
                long amount=getMaxByPlatformForOperator(vo);
                vo.setAvailableCredit(amount);
            }
        }
        return listByJoinuserId;
    }

    @Override
    public void updateForSlApplyLoan(long amount, int joinid, String idofpaynow, TbSlLoanCreditVoForFront vo, int idOfTbFactoryingOperator, String mhtnofrom, String voucher,int idOfTbFactoryingCompany) throws BusinessException {
    	String notcompleteCount = tbSlLoanCreditService.selectNotcompleteCreditLoanByJoinid(joinid); 
    	if (CommonUtils.getInt(notcompleteCount) > 0)
    		throw new BusinessException("该用户还有未完成的贷款记录，请完成后重试.");
    	
    	TbSlCreditControll tbSlCreditControllVo=vo.getTbSlCreditControll();
        List<TbSlLoanCreditVo> listvo=vo.getListvo();
        if(CommonUtils.isEmpty(listvo)){
            throw new BusinessException("申请贷款失败");
        }

        if(!CommonUtils.isEmpty(tbSlCreditControllVo)){
                tbSlLoanCreditService.lockById(tbSlCreditControllVo.getId());
                dataVersionValidationService.validateVO(tbSlCreditControllVo.getId(),"tb_sl_credit_controll",tbSlCreditControllVo.getRowUpdateTime() );
            }

        String  canloanamount=getMaxLoanAmount(joinid,ISLConstDef.OPERATOR_TYPE);
        if(amount>CommonUtils.getLong(canloanamount)){
            throw new BusinessException("您所输入的金额大于可提现额");
        }
        List<TbSlLoanCreditLog> creditLogList=autoGenerationCredit(amount, joinid, idofpaynow,ISLConstDef.OPERATOR_TYPE);
        if(!CommonUtils.isEmpty(creditLogList)){
            String targetPDFFileFolder = FileUploadUtils.getDefaultBaseDir()
                    + File.separator + ISLConstDef.slLoanApplyGenFileDir;
            //后台融资补录需要调用此方法来获得融资编号，但没有选择收款银行，因此参数bankacc传入null
            String[] s = slservice.generateSLLoanApplyFile(joinid, null, creditLogList,
                    targetPDFFileFolder);
            String contractfilepath = ISLConstDef.slLoanApplyGenFileDir
                    + File.separator + FileUploadUtils.getFileNameFromPath(s[0]);
            int i=1;
            for(TbSlLoanCreditLog logvo:creditLogList){
                //String expireddate=TimeUtils.getDateAfterDays(Integer.parseInt(maxdays));
                logvo.setCode(s[i]);
                logvo.setMaterialDownload(contractfilepath);
                logvo .setCreditstatus(IConstDef.LOAN_TYPE_OF_NOTPAY);
                logvo.setRealLoanTime(TimeUtils.getCurDate());
                logvo.setCalculateDate(TimeUtils.getCurDate());
//                logvo.setLastRefundTime();
                logvo.setVoucher(voucher);
                logvo.setUserIdOfIPayNowOfCreditor(mhtnofrom);
                logvo.setIdOfTbFactoryingOperator(idOfTbFactoryingOperator);
                logvo.setIdOfTbFactoryingCompany(idOfTbFactoryingCompany);
                i++;
            }
            try{
            tbSlLoanCreditService.insertBatch(creditLogList);
            }catch (Exception e){
                throw new BusinessException("放款失败",e);
            }
            if(CommonUtils.isEmpty(vo.getRowUpdateTime())){
                updateLoanStat(amount,joinid,vo.getIdofloaninfo(),null);
            } else{
               updateLoanStat(amount,joinid,vo.getIdofloaninfo(),TimeUtils.getDateString(vo.getRowUpdateTime()));
            }
            uploadFileService.updateStatusById(CommonUtils.getInt(voucher),IConstDef.UPLOADSTATUS_COMMITED);
    }
    }


    private long generateRefund(TbSlLoanInfo info,TbSlLoanCreditLog creditLog, TbSlLoanApplication appvo, long amount, int joinid,List<TbSlRefundVo> list) throws BusinessException {
        String  totalNotPaybackAmount=creditLog.getTotalNotPaybackAmount();
        String  totalNotPaybackFee=creditLog.getTotalNotPaybackFee();
        String  totalNotPaybackRate=creditLog.getTotalNotPaybackRate();
        String  totalNotPaybackRenewedRate=creditLog.getTotalNotPaybackRenewedRate();
        String  totalNotPaybackRenewedFee=creditLog.getTotalNotPaybackRenewedFee();
        String  totalNotPaybackPenalty=creditLog.getTotalNotPaybackPenalty();
        String  totalNotPaybackRenewedAmount=creditLog.getTotalNotPaybackRenewedAmount();
        long  totalNotPaybackAmountlong=CommonUtils.getLong(totalNotPaybackAmount);
        long  totalNotPaybackFeelong=CommonUtils.getLong(totalNotPaybackFee);
        long  totalNotPaybackRatelong=CommonUtils.getLong(totalNotPaybackRate);
        long  totalNotPaybackRenewedRatelong=CommonUtils.getLong(totalNotPaybackRenewedRate);
        long  totalNotPaybackRenewedFeelong=CommonUtils.getLong(totalNotPaybackRenewedFee);
        long  totalNotPaybackPenaltylong=CommonUtils.getLong(totalNotPaybackPenalty);
        long  totalNotPaybackRenewedAmountlong=0;
        long totalPay=totalNotPaybackAmountlong+totalNotPaybackFeelong
                +totalNotPaybackRatelong;
        if(TimeUtils.getCurDate().compareTo(creditLog.getLastRefundTime())>0){     //过了最长还款期才加上展期的服务费和利息和发信息
            totalNotPaybackRenewedAmountlong=CommonUtils.getLong(totalNotPaybackRenewedAmount);
            totalPay=totalPay+totalNotPaybackRenewedAmountlong+totalNotPaybackRenewedRatelong+
                    totalNotPaybackRenewedFeelong+totalNotPaybackPenaltylong;

        }
        if(totalPay<=amount){
            //新增一条还款记录
            TbSlRefundCreditVo refundCreditVo=new TbSlRefundCreditVo();
            refundCreditVo.setCode(creditLog.getCode());
            refundCreditVo.setRefundPrinciple(new Long(totalNotPaybackAmountlong).toString());
            refundCreditVo.setRefundFee(new Long(totalPay-totalNotPaybackAmountlong-totalNotPaybackRenewedAmountlong).toString());
            refundCreditVo.setRefundRenewedAmount(new Long(totalNotPaybackRenewedAmountlong).toString());
            refundCreditVo.setTotalNotPaybackAmount(new Long(totalNotPaybackAmountlong).toString());
            refundCreditVo.setTotalNotPaybackRate(new Long(totalPay-totalNotPaybackAmountlong-totalNotPaybackRenewedAmountlong).toString());
            refundCreditVo.setTotalNotPaybackRenewedAmount(new Long(totalNotPaybackRenewedAmountlong).toString());
            BigDecimal rate=new BigDecimal("0");
            if(!CommonUtils.isEmpty(creditLog.getFee())){
                rate= rate.add(new BigDecimal(creditLog.getFee()));
            }
            if(!CommonUtils.isEmpty(creditLog.getRate())){
                rate=rate.add(new BigDecimal(creditLog.getRate()));
            }
            refundCreditVo.setFee(rate.toString());
            refundCreditVo.setRealLoanDate(creditLog.getRealLoanTime());
            TbSlRefundVo tbSlRefundVo=new TbSlRefundVo();
            tbSlRefundVo.setTbslrefundcreditvo(refundCreditVo);
            TbSlLoanCreditLogForFront tbSlLoanCreditLogForFront=new TbSlLoanCreditLogForFront();
            tbSlLoanCreditLogForFront.setId(creditLog.getId());
            tbSlLoanCreditLogForFront.setRowUpdateTime(creditLog.getRowUpdateTime());
            tbSlRefundVo.setCreditVo(tbSlLoanCreditLogForFront);
            list.add(tbSlRefundVo);

                    //更改金额 -本次还的本金-本次还的利息
            amount=amount-totalPay;

        }else{
            totalPay=amount;
            try{
                long repayRenewedAmount=0;
                long repayPenalty=0;
                long repayRenewedRate=0;
                long repayRenewedFee=0;

                if(amount>0&&TimeUtils.getCurDate().compareTo(creditLog.getLastRefundTime())>0){
                    if(totalNotPaybackRenewedAmountlong<=amount){
                        repayRenewedAmount=totalNotPaybackRenewedAmountlong;
                        amount=amount-totalNotPaybackRenewedAmountlong;
                    }else{
                        repayRenewedAmount=amount;
                        amount=0;
                    }
                }
                if(amount>0&&TimeUtils.getCurDate().compareTo(creditLog.getLastRefundTime())>0){
                    if(totalNotPaybackPenaltylong<=amount){
                        repayPenalty=totalNotPaybackPenaltylong;
                        amount=amount-totalNotPaybackPenaltylong;
                    }else{
                        repayPenalty=amount;
                        amount=0;
                    }

                }
                if(amount>0&&TimeUtils.getCurDate().compareTo(creditLog.getLastRefundTime())>0){
                    if(totalNotPaybackRenewedFeelong<=amount){
                        repayRenewedFee=totalNotPaybackRenewedFeelong;
                        amount=amount-totalNotPaybackRenewedFeelong;
                    }else{
                        repayRenewedFee=amount;
                        amount=0;
                    }
                }
                if(amount>0&&TimeUtils.getCurDate().compareTo(creditLog.getLastRefundTime())>0){
                    if(totalNotPaybackRenewedRatelong<=amount){
                        repayRenewedRate=totalNotPaybackRenewedRatelong;
                        amount=amount-totalNotPaybackRenewedRatelong;
                    }else{
                        repayRenewedRate=amount;
                        amount=0;
                    }
                }
                String endtime=TimeUtils.getCurDate();
                if(endtime.compareTo(creditLog.getLastRefundTime())>0){
                  endtime=TimeUtils.getDateAfterDays(creditLog.getLastRefundTime(),1);
                }
                Map<String,Long> map=CommonUtils.getAmountAndFee(new Long(amount).toString(),creditLog.getRealLoanTime(),endtime,creditLog.getFee(),creditLog.getRate());
                long principal=map.get("principal");
                long fee=map.get("fee");
                long radio=map.get("ratio" );
                if(fee>totalNotPaybackFeelong){
                    fee=totalNotPaybackFeelong;
                    radio=radio+fee-totalNotPaybackFeelong;
                }
                if(radio>totalNotPaybackRatelong){
                    long newradio=totalNotPaybackRatelong;
                   // radio=totalNotPaybackRatelong;
                    if(principal<(totalNotPaybackAmountlong+radio-newradio)) {
                        principal=principal+radio-newradio;
                    }
                    radio=newradio;
                }


                //新增还款信息
                TbSlRefundCreditVo vo=new TbSlRefundCreditVo();
                vo.setCode(creditLog.getCode());
                BigDecimal rate=new BigDecimal("0");
                if(!CommonUtils.isEmpty(creditLog.getFee())){
                     rate=rate.add(new BigDecimal(creditLog.getFee()));
                }
                if(!CommonUtils.isEmpty(creditLog.getRate())){
                      rate=rate.add(new BigDecimal(creditLog.getRate()));
                }
                vo.setFee(rate.toString());
                vo.setTotalNotPaybackAmount(creditLog.getTotalNotPaybackAmount());
                long totalnotpaybackrate=totalNotPaybackFeelong
                        + totalNotPaybackRatelong;
                if(TimeUtils.getCurDate().compareTo(creditLog.getLastRefundTime())>0){
                    totalnotpaybackrate=totalnotpaybackrate+totalNotPaybackRenewedRatelong +
                            totalNotPaybackRenewedFeelong + totalNotPaybackPenaltylong;
                }
                vo.setTotalNotPaybackRate(new Long(totalnotpaybackrate).toString());
                vo.setTotalNotPaybackRenewedAmount(new Long(totalNotPaybackRenewedAmountlong).toString());
                vo.setRealLoanDate(creditLog.getRealLoanTime());
                vo.setRefundPrinciple(new Long(principal).toString());
                vo.setRefundFee(new Long(radio+fee+repayPenalty+repayRenewedFee+repayRenewedRate).toString());
                vo.setRefundRenewedAmount(new Long(repayRenewedAmount).toString());
                TbSlRefundVo  tbSlRefundVo=new TbSlRefundVo();
                tbSlRefundVo.setTbslrefundcreditvo(vo);
                TbSlLoanCreditLogForFront tbSlLoanCreditLogForFront=new TbSlLoanCreditLogForFront();
                tbSlLoanCreditLogForFront.setId(creditLog.getId());
                tbSlLoanCreditLogForFront.setRowUpdateTime(creditLog.getRowUpdateTime());
                tbSlRefundVo.setCreditVo(tbSlLoanCreditLogForFront);
                list.add(tbSlRefundVo);
                amount=0;
            }catch (Exception e){
                throw  new BusinessException("系统异常",e);
            }
        }
        return amount;



    }
    @Override
    public long updateRepayOneByOneLoan(TbSlLoanCreditLog creditLog, TbSlLoanApplication appvo, long amount, int joinid, String orderid,TbSlLoanInfo loanInfo,String ventor,String applydate)throws BusinessException {
        String  loantotalPayBackAmount=loanInfo.getTotalPayBackAmount();
        String  loantotalInterestRate=loanInfo.getTotalInterestRate();
        String  loantotalNotPaybackAmount=loanInfo.getTotalNotPaybackAmount();
        String  loantotalNotPaybackRate=loanInfo.getTotalNotPaybackRate();
        String  loantotalNotPaybackFee=loanInfo.getTotalNotPaybackFee();
        String  loantotalInterestFee=loanInfo.getTotalInterestFee();
        String  loantotalNotPaybackRenewedFee=loanInfo.getTotalNotPaybackRenewedFee();
        String  loantotalInterestRenewedFee=loanInfo.getTotalInterestRenewedFee();
        String  loantotalNotPaybackRenewedRate=loanInfo.getTotalNotPaybackRenewedRate();
        String  loantotalInterestRenewedRate=loanInfo.getTotalInterestRenewedRate();
        String  loantotalPaybackRenewedAmount=loanInfo.getTotalPaybackRenewedAmount();
        String  loantotalNotPaybackRenewedAmount=loanInfo.getTotalNotPaybackRenewedAmount();
        String  loantotaltotalInterestPenalty=loanInfo.getTotalInterestPenalty();
        String  loantotalNotPaybackPenalty=loanInfo.getTotalNotPaybackPenalty();
        long loantotalPayBackAmountllong=CommonUtils.getLong(loantotalPayBackAmount);
        long loantotalInterestRatelong=CommonUtils.getLong(loantotalInterestRate);
        if(CommonUtils.isEmpty(loantotalNotPaybackAmount)){
            throw new BusinessException("贷款信息表里供应商没有贷款金额，请校账");
        }
        long loantotalNotPaybackAmountlong=CommonUtils.getLong(loantotalNotPaybackAmount);
        long loantotalNotPaybackRatelong=CommonUtils.getLong(loantotalNotPaybackRate);
        long  loantotalNotPaybackFeelong=CommonUtils.getLong(loantotalNotPaybackFee);
        long  loantotalInterestFeelonglong=CommonUtils.getLong(loantotalInterestFee);
        long  loantotalNotPaybackRenewedFeelong=CommonUtils.getLong(loantotalNotPaybackRenewedFee);
        long  loantotalInterestRenewedFeelong=CommonUtils.getLong(loantotalInterestRenewedFee);
        long  loantotalNotPaybackRenewedRatelong=CommonUtils.getLong(loantotalNotPaybackRenewedRate);
        long  loantotalInterestRenewedRatelong=CommonUtils.getLong(loantotalInterestRenewedRate);
        long  loantotalPaybackRenewedAmountlong=CommonUtils.getLong(loantotalPaybackRenewedAmount);
        long  loantotalNotPaybackRenewedAmountlong=CommonUtils.getLong(loantotalNotPaybackRenewedAmount);
        long  loantotaltotalInterestPenaltylong=CommonUtils.getLong(loantotaltotalInterestPenalty);
        long  loantotalNotPaybackPenaltylong=CommonUtils.getLong(loantotalNotPaybackPenalty);
        String  totalNotPaybackAmount=creditLog.getTotalNotPaybackAmount();
        String  totalNotPaybackFee=creditLog.getTotalNotPaybackFee();
        String  totalNotPaybackRate=creditLog.getTotalNotPaybackRate();
        String  totalNotPaybackRenewedRate=creditLog.getTotalNotPaybackRenewedRate();
        String  totalNotPaybackRenewedFee=creditLog.getTotalNotPaybackRenewedFee();
        String  totalNotPaybackPenalty=creditLog.getTotalNotPaybackPenalty();
        String  totalNotPaybackRenewedAmount=creditLog.getTotalNotPaybackRenewedAmount();
        long  totalNotPaybackAmountlong=CommonUtils.getLong(totalNotPaybackAmount);
        long  totalNotPaybackFeelong=CommonUtils.getLong(totalNotPaybackFee);
        long  totalNotPaybackRatelong=CommonUtils.getLong(totalNotPaybackRate);
        long  totalNotPaybackRenewedRatelong=CommonUtils.getLong(totalNotPaybackRenewedRate);
        long  totalNotPaybackRenewedFeelong=CommonUtils.getLong(totalNotPaybackRenewedFee);
        long  totalNotPaybackPenaltylong=CommonUtils.getLong(totalNotPaybackPenalty);
        long  totalNotPaybackRenewedAmountlong=0;
        if(TimeUtils.getCurDate().compareTo(creditLog.getLastRefundTime())>0){
            totalNotPaybackRenewedAmountlong=CommonUtils.getLong(totalNotPaybackRenewedAmount);
        }
        long totalPay=totalNotPaybackAmountlong+totalNotPaybackFeelong
                +totalNotPaybackRatelong+totalNotPaybackRenewedRatelong+
                totalNotPaybackRenewedFeelong+totalNotPaybackPenaltylong+
                totalNotPaybackRenewedAmountlong;
        long totalintrest=tbSlLoanRefundService.queryTotalInterest(creditLog.getId());
        TbSlLoanRefundLog refundLog=new TbSlLoanRefundLog();
        if(totalPay<=amount){
            //新增一条还款记录
            refundLog.setRefundPrinciple(new Long(totalNotPaybackAmountlong).toString());
            refundLog.setRefundFee(new Long(totalNotPaybackFeelong).toString());
            refundLog.setRefundRate(new Long(totalNotPaybackRatelong).toString());
            refundLog.setRefundRenewedFee(new Long(totalNotPaybackRenewedFeelong).toString());
            if(TimeUtils.getCurDate().compareTo(creditLog.getLastRefundTime())>0){
            refundLog.setRefundRenewedAmount(new Long(totalNotPaybackRenewedAmountlong).toString());
            }else{
                refundLog.setRefundRenewedAmount(new Long(0).toString());
            }
            refundLog.setRefundRenewedRate(new Long(totalNotPaybackRenewedRatelong).toString());
            refundLog.setRefundPenalty(new Long(totalNotPaybackPenaltylong).toString());
            refundLog.setRefundRenewedAmount(new Long(totalNotPaybackRenewedAmountlong).toString());
            refundLog.setUserIdOfJoinOfDebtor(creditLog.getUserIdOfJoinOfDebtor());
            if(CommonUtils.isEmpty(applydate)){
            refundLog.setRefundDate(TimeUtils.getCurDate());
            }else{
                refundLog.setRefundDate(applydate);
            }

            refundLog.setRefundOrderId(orderid);
            refundLog.setIdSlLoanCreditLog(creditLog.getId());
            refundLog.setUserIdOfJoinOfCreditor(creditLog.getUserIdOfJoinOfCreditor());
            refundLog.setShouldRefundPrinciple(new Long(totalNotPaybackAmountlong).toString());
            refundLog.setShouldRefundRate(new Long(totalNotPaybackFeelong + totalNotPaybackRatelong + totalNotPaybackRenewedFeelong  + totalNotPaybackRenewedRatelong + totalNotPaybackPenaltylong).toString());
            refundLog.setIdOfPlatform(creditLog.getIdOfPlatform());
//            refundLog.setTotalInterestRate(new Long(totalintrest+totalNotPaybackFeelong+totalNotPaybackRatelong+totalNotPaybackRenewedFeelong+totalNotPaybackRenewedAmountlong+totalNotPaybackRenewedRatelong+totalNotPaybackPenaltylong).toString());
            refundLog.setRefundOrderId(orderid);
            refundLog.setRefundAmount(new Long(totalPay).toString());
            refundLog.setVoucher(ventor);
            refundLog.setPentyIntrest(new Long(totalNotPaybackPenaltylong).toString());
            refundLog.setRenewedIntrest(new Long(totalNotPaybackRenewedFeelong+totalNotPaybackRenewedRatelong).toString());
            refundLog.setRenewedAmount(new Long(totalNotPaybackRenewedAmountlong).toString());
            refundLog.setNormalIntrest(new Long(totalNotPaybackFeelong+totalNotPaybackRatelong).toString());
                                                             //修改贷款记录
            creditLog.setTotalNotPaybackFee("0");
            creditLog.setTotalNotPaybackAmount("0");
            creditLog.setTotalNotPaybackRate("0");
            creditLog.setTotalNotPaybackPenalty("0");
            creditLog.setTotalNotPaybackRenewedAmount("0");
            creditLog.setTotalNotPaybackRenewedFee("0");
            creditLog.setTotalNotPaybackRenewedRate("0");
            creditLog.setCreditstatus(IConstDef.LOAN_TYPE_OF_PAYALL);

            //更改贷款总表的信息
            loantotalPayBackAmountllong=loantotalPayBackAmountllong+totalNotPaybackAmountlong;
            loantotalInterestRatelong=loantotalInterestRatelong+totalNotPaybackRatelong;
            loantotalNotPaybackAmountlong=loantotalNotPaybackAmountlong-totalNotPaybackAmountlong;
            loantotalNotPaybackRatelong=loantotalNotPaybackRatelong-totalNotPaybackRatelong;
            if(loantotalNotPaybackAmountlong<0||loantotalNotPaybackRatelong<0){
                throw  new BusinessException("供应商贷款表未还的本金和未还的利息为负数，请校账joinid"+joinid);
            }
            loantotalNotPaybackFeelong=loantotalNotPaybackFeelong-totalNotPaybackFeelong;
            loantotalInterestFeelonglong=loantotalInterestFeelonglong+totalNotPaybackFeelong;
            loantotalNotPaybackRenewedFeelong=loantotalNotPaybackRenewedFeelong-totalNotPaybackRenewedFeelong;
            loantotalInterestRenewedFeelong=loantotalInterestRenewedFeelong+totalNotPaybackRenewedFeelong;
            loantotalNotPaybackRenewedRatelong=loantotalNotPaybackRenewedRatelong-totalNotPaybackRenewedRatelong;
            loantotalInterestRenewedRatelong=loantotalInterestRenewedRatelong+totalNotPaybackRenewedRatelong;
            loantotalPaybackRenewedAmountlong=loantotalPaybackRenewedAmountlong+totalNotPaybackRenewedAmountlong;
            loantotalNotPaybackRenewedAmountlong=loantotalNotPaybackRenewedAmountlong- totalNotPaybackRenewedAmountlong;
            loantotaltotalInterestPenaltylong=loantotaltotalInterestPenaltylong+totalNotPaybackPenaltylong;
            loantotalNotPaybackPenaltylong=loantotalNotPaybackPenaltylong-totalNotPaybackPenaltylong;
            //更改金额 -本次还的本金-本次还的利息
            amount=amount-totalPay;


        }else{
            totalPay=amount;
            try{
                long repayRenewedAmount=0;
                long repayPenalty=0;
                long repayRenewedRate=0;
                long repayRenewedFee=0;
                if(amount>0){
                    if(totalNotPaybackRenewedAmountlong<=amount){
                        repayRenewedAmount=totalNotPaybackRenewedAmountlong;
                        amount=amount-totalNotPaybackRenewedAmountlong;
                    }else{
                        repayRenewedAmount=amount;
                        amount=0;
                    }
                }
                if(amount>0){
                    if(totalNotPaybackPenaltylong<=amount){
                        repayPenalty=totalNotPaybackPenaltylong;
                        amount=amount-totalNotPaybackPenaltylong;
                    }else{
                        repayPenalty=amount;
                        amount=0;
                    }

                }
                if(amount>0){
                    if(totalNotPaybackRenewedFeelong<=amount){
                        repayRenewedFee=totalNotPaybackRenewedFeelong;
                        amount=amount-totalNotPaybackRenewedFeelong;
                    }else{
                        repayRenewedFee=amount;
                        amount=0;
                    }
                }
                if(amount>0){
                    if(totalNotPaybackRenewedRatelong<=amount){
                        repayRenewedRate=totalNotPaybackRenewedRatelong;
                        amount=amount-totalNotPaybackRenewedRatelong;
                    }else{
                        repayRenewedRate=amount;
                        amount=0;
                    }
                }
                String endtime=TimeUtils.getCurDate();
                if(endtime.compareTo(creditLog.getLastRefundTime())>0){
                    endtime=TimeUtils.getDateAfterDays(creditLog.getLastRefundTime(),1);
                }
                Map<String,Long> map=CommonUtils.getAmountAndFee(new Long(amount).toString(),creditLog.getRealLoanTime(),endtime,creditLog.getFee(),creditLog.getRate());
                long principal=map.get("principal");
                long fee=map.get("fee");
                long radio=map.get("ratio" );
                if(fee>totalNotPaybackFeelong){
                    fee=totalNotPaybackFeelong;
                    radio=radio+fee-totalNotPaybackFeelong;
                }
                if(radio>totalNotPaybackRatelong){
                    long newradio=totalNotPaybackRatelong;
                    if(principal<(totalNotPaybackAmountlong+radio-newradio)) {
                        principal=principal+radio-newradio;
                    }
                    radio=newradio;
                }


                //新增还款信息
                refundLog.setRefundPrinciple(new Long(principal).toString());
                refundLog.setRefundFee(new Long(fee).toString());
                refundLog.setRefundPenalty(new Long(repayPenalty).toString());
                refundLog.setRefundRate(new Long(radio).toString());
                refundLog.setRefundRenewedRate(new Long(repayRenewedRate).toString());
                refundLog.setRefundRenewedAmount(new Long(repayRenewedAmount).toString());
                refundLog.setRefundRenewedFee(new Long(repayRenewedFee).toString());
                refundLog.setUserIdOfJoinOfDebtor(creditLog.getUserIdOfJoinOfDebtor());
                refundLog.setIdOfPlatform(creditLog.getIdOfPlatform());
                refundLog.setRefundDate(TimeUtils.getCurDate());
                refundLog.setRefundOrderId(orderid);
                refundLog.setIdSlLoanCreditLog(creditLog.getId());
                refundLog.setUserIdOfJoinOfCreditor(creditLog.getUserIdOfJoinOfCreditor());
                refundLog.setShouldRefundPrinciple(creditLog.getTotalNotPaybackAmount());
                refundLog.setShouldRefundRate(new Long(totalNotPaybackFeelong
                        + totalNotPaybackRatelong + totalNotPaybackRenewedRatelong +
                        totalNotPaybackRenewedFeelong + totalNotPaybackPenaltylong).toString());
                refundLog.setPentyIntrest(new Long(totalNotPaybackPenaltylong).toString());
                refundLog.setRenewedIntrest(new Long(totalNotPaybackRenewedFeelong+totalNotPaybackRenewedRatelong).toString());
                refundLog.setRenewedAmount(new Long(totalNotPaybackRenewedAmountlong).toString());
                refundLog.setNormalIntrest(new Long(totalNotPaybackFeelong+totalNotPaybackRatelong).toString());
                refundLog.setRefundAmount(new Long(totalPay).toString());
                refundLog.setVoucher(ventor);
                //修改贷款记录
                creditLog.setTotalNotPaybackFee(new Long(totalNotPaybackFeelong - fee).toString());
                creditLog.setTotalNotPaybackRate(new Long(totalNotPaybackRatelong-radio).toString());
                creditLog.setTotalNotPaybackAmount(new Long(totalNotPaybackAmountlong - principal).toString());
                creditLog.setTotalNotPaybackRenewedRate(new Long(totalNotPaybackRenewedRatelong - repayRenewedRate).toString());
                creditLog.setTotalNotPaybackRenewedFee(new Long(totalNotPaybackRenewedFeelong - repayRenewedFee).toString());
                creditLog.setTotalNotPaybackPenalty(new Long(totalNotPaybackPenaltylong-repayPenalty).toString());
                creditLog.setTotalNotPaybackRenewedAmount(new Long(totalNotPaybackRenewedAmountlong-repayRenewedAmount).toString());
                creditLog.setCreditstatus(IConstDef.LOAN_TYPE_OF_PAYPARTMENT);
                //更改贷款总表的信息
                loantotalPayBackAmountllong=loantotalPayBackAmountllong+principal;
                loantotalInterestRatelong=loantotalInterestRatelong+radio;
                loantotalNotPaybackAmountlong=loantotalNotPaybackAmountlong-principal;
                loantotalNotPaybackRatelong=loantotalNotPaybackRatelong-radio;
                loantotalInterestFeelonglong=loantotalInterestFeelonglong+fee;
                loantotalNotPaybackFeelong=loantotalNotPaybackFeelong-fee;
                loantotalInterestRenewedFeelong= loantotalInterestRenewedFeelong+repayRenewedFee;
                loantotalNotPaybackRenewedFeelong= loantotalNotPaybackRenewedFeelong-repayRenewedFee;
                loantotalNotPaybackRenewedAmountlong= loantotalNotPaybackRenewedAmountlong-repayRenewedAmount;
                loantotalPaybackRenewedAmountlong=loantotalPaybackRenewedAmountlong+repayRenewedAmount;
                loantotalInterestRenewedRatelong= loantotalInterestRenewedRatelong+repayRenewedRate;
                loantotalNotPaybackRenewedRatelong=loantotalNotPaybackRenewedRatelong-repayRenewedRate;
                loantotalNotPaybackPenaltylong=loantotalNotPaybackPenaltylong-repayPenalty;
                loantotaltotalInterestPenaltylong= loantotaltotalInterestPenaltylong+repayPenalty;

                if(loantotalNotPaybackAmountlong<0||loantotalNotPaybackRatelong<0){
                    throw  new BusinessException("供应商贷款表未还的本金和未还的利息为负数，请校账joinid"+joinid);
                }
                amount=0;
            }catch (Exception e){
                LogUtils.getSlloanLog().error("金额转化本金和利息出错"+e.getMessage());
                throw  new BusinessException("金额转化本金和利息出错");
            }


        }
       
        Map<String,Object> creditparamap=new HashMap<String, Object>();
        creditparamap.put("totalNotPaybackAmount",creditLog.getTotalNotPaybackAmount());
        creditparamap.put("totalNotPaybackFee",creditLog.getTotalNotPaybackFee());
        creditparamap.put("totalNotPaybackRate",creditLog.getTotalNotPaybackRate());
        creditparamap.put("totalNotPaybackRenewedRate",creditLog.getTotalNotPaybackRenewedRate());
        creditparamap.put("totalNotPaybackRenewedFee",creditLog.getTotalNotPaybackRenewedFee());
        creditparamap.put("totalNotPaybackPenalty",creditLog.getTotalNotPaybackPenalty());
        creditparamap.put("totalNotPaybackRenewedAmount",creditLog.getTotalNotPaybackRenewedAmount());
        creditparamap.put("creditstatus",creditLog.getCreditstatus());
        creditparamap.put("id",creditLog.getId());
        creditparamap.put("rowUpdateTime",TimeUtils.getDateString(creditLog.getRowUpdateTime()));
        tbSlLoanCreditService.updateTbSlLoanCredit(creditparamap);
        loanInfo.setTotalPayBackAmount(new Long(loantotalPayBackAmountllong).toString());
        loanInfo.setTotalInterestRate(new Long(loantotalInterestRatelong).toString());
        loanInfo.setTotalNotPaybackAmount(new Long(loantotalNotPaybackAmountlong).toString());
        loanInfo.setTotalNotPaybackRate(new Long(loantotalNotPaybackRatelong).toString());
        loanInfo.setTotalInterestFee(new Long(loantotalInterestFeelonglong).toString()) ;
        loanInfo.setTotalNotPaybackFee(new Long(loantotalNotPaybackFeelong).toString());
        loanInfo.setTotalNotPaybackRenewedAmount(new Long(loantotalNotPaybackRenewedAmountlong).toString());
        loanInfo.setTotalPaybackRenewedAmount(new Long(loantotalPaybackRenewedAmountlong).toString());
        loanInfo.setTotalInterestPenalty(new Long(loantotaltotalInterestPenaltylong).toString());
        loanInfo.setTotalNotPaybackPenalty(new Long(loantotalNotPaybackPenaltylong).toString());
        loanInfo.setTotalNotPaybackRenewedRate(new Long(loantotalNotPaybackRenewedRatelong).toString());
        loanInfo.setTotalNotPaybackRenewedFee(new Long(loantotalNotPaybackRenewedFeelong).toString()) ;
        loanInfo.setTotalInterestRenewedFee(new Long(loantotalInterestRenewedFeelong).toString());
        loanInfo.setTotalInterestRenewedRate(new Long(loantotalInterestRenewedRatelong).toString());
        tbSlLoanRefundService.insert(refundLog);
        return amount;

    }

    @Override
    public void exportSLLoanReportExcelFile(int joinuserid, OutputStream outputStream) throws BusinessException {
    	TbMerchantInfo infovo = infoBaseService.queryInfoByJoinId(joinuserid);
    	List<TbSlLoanCreditLog> creditList = tbSlLoanCreditService.queryCreditByJoinid(joinuserid, null);
    	List<TbSlLoanRefundVo> refundList = tbSlLoanRefundService.queryLoanRefundlist(joinuserid, null);
    	TbSlLoanInfo loaninfovo = tbSlLoanInfoService.queryLoanInfoByJoinid(joinuserid);
    	List<TbSlCreditLogForExcelVO> renewedCreditList = tbSlLoanCreditService.queryCreditForExcel(joinuserid);
    	List<TbSlLoanRefundVo> renewedRefundList = tbSlLoanRefundService.queryRenewedRefundForExcel(joinuserid);
//    	if (renewedRefundList == null || renewedRefundList.size() == 0) {
//    		renewedRefundList = new ArrayList<TbSlLoanRefundVo>();
//    		renewedRefundList.add(CommonUtils.creatRandomObject(TbSlLoanRefundVo.class, null));
//    		renewedRefundList.add(CommonUtils.creatRandomObject(TbSlLoanRefundVo.class, null));
//    		renewedRefundList.add(CommonUtils.creatRandomObject(TbSlLoanRefundVo.class, null));
//    		renewedRefundList.add(CommonUtils.creatRandomObject(TbSlLoanRefundVo.class, null));
//    	}
    	
    	String currdate = TimeUtils.getCurDate();
    	SlDailyBalanceReport reportvo = new SlDailyBalanceReport();
    	reportvo.setBalancedate(currdate);
    	reportvo.setMerchantusername(infovo.getMchName());
    	
    	if (creditList != null && creditList.size() > 0) {
    		List<SLDailyCreditVO> report_creditlist = new ArrayList<SLDailyCreditVO>();
    		for(TbSlLoanCreditLog creditlogvo : creditList) {
    			SLDailyCreditVO creditvo = new SLDailyCreditVO();
    			creditvo.setCreditdate(creditlogvo.getRealLoanTime());
    			creditvo.setCreditno(creditlogvo.getCode());
    			creditvo.setDayfee(new BigDecimal(creditlogvo.getFee()).toString());
    			creditvo.setExpirydate(creditlogvo.getLastRefundTime());
    			creditvo.setPrinciple(CommonUtils.getFenByString(creditlogvo.getAccountDelta()));
    			creditvo.setUnrefund_principle(CommonUtils.getFenByString(creditlogvo.getTotalNotPaybackAmount()));
    			creditvo.setUnrefund_rate(CommonUtils.getFenByString(creditlogvo.getTotalNotPaybackFee()));
    			
    			String rate_sale = tbSlLoanFloatService.queryAmountByCreditId(creditlogvo.getId());
    			creditvo.setUnrefund_rate_sale(CommonUtils.getFenByString(rate_sale));
    			
    			String rate_salememo = tbSlLoanFloatService.queryMemoByCreditId(creditlogvo.getId());
    			creditvo.setUnrefund_rate_salememo(rate_salememo);
    			report_creditlist.add(creditvo);
    		}
    		reportvo.setCreditlist(report_creditlist);
    	}
    	
    	if (refundList != null && refundList.size() > 0) {
    		List<SLDailyRefundVO> report_refundlist = new ArrayList<SLDailyRefundVO>();
    		for(TbSlLoanRefundVo refundlogvo : refundList) {
    			SLDailyRefundVO refundvo = new SLDailyRefundVO();
    			refundvo.setCreditno(refundlogvo.getLoanCode());
    			refundvo.setNendrefund_principle(CommonUtils.getFenByString(refundlogvo.getShouldRefundPrinciple()));
    			refundvo.setNendrefund_rate(CommonUtils.getFenByString(refundlogvo.getShouldRefundRate()));
    			refundvo.setRatedaycount(refundlogvo.getDays() + "");
    			refundvo.setRefund_amount(CommonUtils.getFenByString(refundlogvo.getRefundAmount()));
    			refundvo.setRefund_date(refundlogvo.getRefundDate());
    			refundvo.setRefund_principle(CommonUtils.getFenByString(refundlogvo.getRefundPrinciple()));
    			refundvo.setRefund_rate(CommonUtils.getFenByString(refundlogvo.getRefundFee()));
    			refundvo.setUnrefund_principle(CommonUtils.getFenByString(refundlogvo.getSurplusPrinciple()));
    			refundvo.setUnrefund_rate(CommonUtils.getFenByString(refundlogvo.getSurplusFee()));
    			report_refundlist.add(refundvo);
    		}
    		reportvo.setRefundlist(report_refundlist);
    	}
    	
    	if (loaninfovo != null) {
    		SLDailyStatVO statvo = new SLDailyStatVO();
    		statvo.setPrinciple(CommonUtils.getFenByString(loaninfovo.getTotalLoanAmount()));
    		statvo.setStatdate(TimeUtils.getCurDate());
//    		statvo.setStatdate(new SimpleDateFormat("yyyy-MM-dd").format(loaninfovo.getRowUpdateTime()));
    		statvo.setTotal_refund_principal(CommonUtils.getFenByString(loaninfovo.getTotalPayBackAmount()));
    		statvo.setTotal_refund_rate(CommonUtils.getFenByString(loaninfovo.getTotalInterestRate()));
    		statvo.setUnrefund_principal(CommonUtils.getFenByString(loaninfovo.getTotalNotPaybackAmount()));
    		statvo.setUnrefund_rate(CommonUtils.getFenByString(loaninfovo.getTotalNotPaybackRate()));
    		statvo.setTotalPaybackRenewedAmount(CommonUtils.getFenByString(loaninfovo.getTotalPaybackRenewedAmount()));
    		statvo.setTotalNotPaybackRenewedAmount(CommonUtils.getFenByString(loaninfovo.getTotalNotPaybackRenewedAmount()));
    		
    		reportvo.setStatvo(statvo);
    	}
    	
		try {
			boolean hassaleFlag = tbSlLoanFloatService.hasFloatByJoinid(joinuserid);
			
			ExcelTmpl et;
			if (renewedCreditList != null && renewedCreditList.size() > 0) {
				reportvo.setRenewedCreditList(renewedCreditList);
				reportvo.setRenewedRefundList(renewedRefundList);
				if (hassaleFlag) {
					et= new ExcelTmpl(ISLConstDef.SLLOANEXCEL_REPORT_RENEWED_HASSALEINFO, outputStream);
				} else { 
					et= new ExcelTmpl(ISLConstDef.SLLOANEXCEL_REPORT_RENEWED, outputStream);
				}
			} else {
				if (hassaleFlag) {
					et= new ExcelTmpl(ISLConstDef.SLLOANEXCEL_REPORT_HASSALEINFO, outputStream);
				} else {
					et= new ExcelTmpl(ISLConstDef.SLLOANEXCEL_REPORT, outputStream);
				}
			}
			et.wrapData(reportvo);
			et.closeWbook();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

    @Override
    public void updateforapplyRenewed(Integer id, String rowUpdateTime, String renewedUpload) throws BusinessException {
        tbSlLoanCreditService.lockById(id);
        dataVersionValidationService.validateVO(id,"tb_sl_loan_credit_log",rowUpdateTime);
        Map<String,Object> paramap=new HashMap<String ,Object>();
        paramap.put("id",id);
        paramap.put("renewedUpload",renewedUpload);
        paramap.put("renewedStatus","N");
        this.tbSlLoanCreditService.updateTbSlLoanCredit(paramap);
        uploadFileService.updateStatusById(CommonUtils.getInt(renewedUpload),IConstDef.UPLOADSTATUS_COMMITED);
    }
    private  boolean isDaySpecial()throws BusinessException{
        GregorianCalendar  calendar=new GregorianCalendar();
        TbWeekend vo=tbWeekEndService.queryWorkDayForWeekend(TimeUtils.getCurDate(), TimeUtils.getCurYear());
        if (calendar.get(GregorianCalendar.DAY_OF_WEEK) != GregorianCalendar.SATURDAY
                && calendar.get(GregorianCalendar.DAY_OF_WEEK) != GregorianCalendar.SUNDAY){
            if(CommonUtils.isEmpty(vo)){
                return false;
            }else{
                return true;
            }
        }else{
            if(CommonUtils.isEmpty(vo)){
                return true;
            }else{
                return false;
            }
        }


    }

    @Override
    public void updateForAgreeRenewed(SlCreditRenewedVo vo) throws BusinessException {
        tbSlLoanCreditService.lockById(vo.getId());
        dataVersionValidationService.validateVO(vo.getId(),"tb_sl_loan_credit_log",vo.getRowUpdateTime());

        Map<String,Object> paramap=new HashMap<String ,Object>();
        paramap.put("id",vo.getId());
        paramap.put("renewedRate",vo.getRenewedRate());
        paramap.put("renewedFee",vo.getRenewedfee());
        paramap.put("renewedRefundTime",vo.getRenewedEndTime());
        paramap.put("renewedBeginTime",vo.getRenewedBegintime());
        BigDecimal amount=new BigDecimal("0");
        if(!CommonUtils.isEmpty(vo.getRenewedAmount())){
            amount=new BigDecimal(vo.getRenewedAmount()).multiply(new BigDecimal(100));
        }
        paramap.put("totalNotPaybackRenewedAmount",amount.longValue());
        paramap.put("renewedStatus","Y");
        this.tbSlLoanCreditService.updateTbSlLoanCredit(paramap);
        TbSlLoanCreditLog logvo=tbSlLoanCreditService.queryCreditLogById(vo.getId());
        TbMerchantInfo infovo=tbMerchantInfoBaseService.queryInfoByJoinId(logvo.getUserIdOfJoinOfDebtor());
        if(!CommonUtils.isEmpty(infovo)&&!CommonUtils.isDev()){
        	if (StringUtils.isEmpty(infovo.getMobile()))
        		return;
        	sendMsg("%code%", logvo.getCode(), ISLConstDef.RENEWED_PASS, infovo.getMobile());
        }
    }
    
    private void sendMsg(String placeholder, String placevalue, String type, String mobile) {
    	if(CommonUtils.isEmpty(mobile))
    		return;
    	
		NotificationTemplate template = notificationTemplateService.findByName(type);
		if (template == null || StringUtils.isEmpty(template.getTemplate()))
			return;
		  
		String msg = template.getTemplate().replace(placeholder, placevalue);
		SMSSendUtil.sendMsg(mobile,msg);
    }
    
    private void sendMsg(String[] placeholder, String[] placevalue, String type, String mobile) {
    	if(CommonUtils.isEmpty(mobile))
    		return;
    	
		NotificationTemplate template = notificationTemplateService.findByName(type);
		if (template == null || StringUtils.isEmpty(template.getTemplate()))
			return;
		 
		String msg = template.getTemplate();
		for(int i=0; i < placeholder.length; i++) {
			msg = msg.replace(placeholder[i], placevalue[i]);
		}
		SMSSendUtil.sendMsg(mobile,msg);
    }

    @Override
    public void updateRefuseRenewed(Integer id, String rowupdatetime, String memo) throws BusinessException {
        tbSlLoanCreditService.lockById(id);
        dataVersionValidationService.validateVO(id,"tb_sl_loan_credit_log",rowupdatetime);
        Map<String,Object> paramap=new HashMap<String ,Object>();
        paramap.put("id",id);
        paramap.put("memo",memo);
        paramap.put("renewedStatus","R");
        this.tbSlLoanCreditService.updateTbSlLoanCredit(paramap);
        TbSlLoanCreditLog logvo=tbSlLoanCreditService.queryCreditLogById(id);
        TbMerchantInfo infovo=tbMerchantInfoBaseService.queryInfoByJoinId(logvo.getUserIdOfJoinOfDebtor());
        if(!CommonUtils.isEmpty(infovo)&&!CommonUtils.isDev()){
            if(!CommonUtils.isEmpty(infovo.getMobile())){
            	sendMsg("%code%", logvo.getCode(), ISLConstDef.RENEWED_REFUSE, infovo.getMobile());
            }
        }
    }

    @Override
    public void updateLoanFloat(TbSlCreditForFloatVo vo) throws BusinessException {
        Integer  id=vo.getId();
        Date creditdate=vo.getRowUpdateTime();
        Integer idofloaninfo=vo.getIdOfLoanInfo();
        Date loants=vo.getLoanInfoTs();
        List<TbSlLoanFloat> list=vo.getList();
        List<TbSlLoanFloat> addlist=new ArrayList<>();
        tbSlLoanCreditService.lockById(id);
        dataVersionValidationService.validateVO(id,"tb_sl_loan_credit_log",creditdate);
        TbSlLoanCreditLog logvo=tbSlLoanCreditService.queryCreditLogById(id);
        tbSlLoanInfoService.lockId(idofloaninfo);
        dataVersionValidationService.validateVO(idofloaninfo,"tb_sl_loan_info",loants);
        TbSlLoanInfo loaninfovo=tbSlLoanInfoService.queryById(idofloaninfo);
        if(!CommonUtils.isEmpty(list)){
        for(TbSlLoanFloat floatvo:list){
            String amount=floatvo.getAmount();
            if(CommonUtils.isEmpty(amount)){
                continue;
            }
            BigDecimal amountdecimal=new BigDecimal(amount).multiply(new BigDecimal(100));
            if(amountdecimal.doubleValue()==0){
                continue;
            }
            floatvo.setAmount(new Long(amountdecimal.longValue()).toString());
            addlist.add(floatvo);
            String type=floatvo.getType();
            if(CommonUtils.isEmpty(type)){
                throw new BusinessException("调息的类型不能为空");
            }
            if(ISLConstDef.FLOAT_TYPE_FEE.equals(type)){
            if(new BigDecimal(logvo.getTotalNotPaybackFee()).longValue()<=0){
               throw new BusinessException("原始利息不能小于等于0");
            }
             BigDecimal totalNotPaybackFeedecimal=new BigDecimal(logvo.getTotalNotPaybackFee()).add(amountdecimal);
             if(totalNotPaybackFeedecimal.doubleValue()<0){
                 throw  new BusinessException("调息过后，未还服务利息小于0,");
             }
             logvo.setTotalNotPaybackFee(new Long(totalNotPaybackFeedecimal.longValue()).toString());
             loaninfovo.setTotalNotPaybackFee(new Long(new BigDecimal(loaninfovo.getTotalNotPaybackFee()).add(amountdecimal).longValue()).toString());
             continue;
            }
            if(ISLConstDef.FLOAT_TYPE_RATE.equals(type)){
                if(new BigDecimal(logvo.getTotalNotPaybackRate()).longValue()<=0){
                    throw new BusinessException("原始利息不能小于等于0");
                }
                BigDecimal totalNotPaybackratedecimal=new BigDecimal(logvo.getTotalNotPaybackRate()).add(amountdecimal);
                if(totalNotPaybackratedecimal.doubleValue()<0){
                    throw new BusinessException("调息过后，未还基础利息小于0");
                }
                logvo.setTotalNotPaybackRate(new Long(totalNotPaybackratedecimal.longValue()).toString());
                loaninfovo.setTotalNotPaybackRate(new Long(new BigDecimal(loaninfovo.getTotalNotPaybackRate()).add(amountdecimal).longValue()).toString());
                continue;
            }
            if(ISLConstDef.FLOAT_TYPE_RENEWEDRATE.equals(type)){
                if(new BigDecimal(logvo.getTotalNotPaybackRenewedRate()).longValue()<=0){
                    throw new BusinessException("原始利息不能小于等于0");
                }
                BigDecimal totalNotPaybackRenewedRate= new BigDecimal(logvo.getTotalNotPaybackRenewedRate()).add(amountdecimal);
                if(totalNotPaybackRenewedRate.doubleValue()<0){
               throw new BusinessException("调息过后，未还展期利息小于0");
               }
                logvo.setTotalNotPaybackRenewedRate(new Long(totalNotPaybackRenewedRate.longValue()).toString());
                loaninfovo.setTotalNotPaybackRenewedRate(new Long(new BigDecimal(loaninfovo.getTotalNotPaybackRenewedRate()).add(amountdecimal).longValue()).toString());
                continue;
            }
            if(ISLConstDef.FlOAT_TYPE_RENEWEDFEE.equals(type)){
                if(new BigDecimal(logvo.getTotalNotPaybackRenewedFee()).longValue()<=0){
                    throw new BusinessException("原始利息不能小于等于0");
                }
                BigDecimal    totalNotPayBackRenewedFeedecimal= new BigDecimal(logvo.getTotalNotPaybackRenewedFee()).add(amountdecimal);
                if(totalNotPayBackRenewedFeedecimal.doubleValue()<0){
                    throw  new BusinessException("调息过后，未还展期服务利息小于0");
                }
                logvo.setTotalNotPaybackRenewedFee(new Long(totalNotPayBackRenewedFeedecimal.longValue()).toString());
                loaninfovo.setTotalNotPaybackRenewedFee(new Long(new BigDecimal(loaninfovo.getTotalNotPaybackRenewedFee()).add(amountdecimal).longValue()).toString());
                continue;
            }
            if(ISLConstDef.FLOAT_TYPE_PENALTY.equals(type)){
                if(new BigDecimal(logvo.getTotalNotPaybackPenalty()).longValue()<=0){
                    throw new BusinessException("原始利息不能小于等于0");
                }
                BigDecimal totalNotPayBackPenaltyDecimal=new BigDecimal(logvo.getTotalNotPaybackPenalty()).add(amountdecimal);
                if(totalNotPayBackPenaltyDecimal.doubleValue()<0){
                    throw  new BusinessException("调息过后罚息值小于0");
                }
                logvo.setTotalNotPaybackPenalty(new Long(totalNotPayBackPenaltyDecimal.longValue()).toString());
                loaninfovo.setTotalNotPaybackPenalty(new Long(new BigDecimal(loaninfovo.getTotalNotPaybackPenalty()).add(amountdecimal).longValue()).toString());
                continue;
            }

        }
            if(addlist!=null&&addlist.size()>0){
            tbSlLoanCreditService.updateByIdSelective(logvo);
            tbSlLoanInfoService.updateByIdSelective(loaninfovo);
            TbSlLoanInfoLog loanInfoLog=new TbSlLoanInfoLog();
            loanInfoLog.setIdOfTbMerchantUser(loaninfovo.getIdOfTbMerchantUser());
            loanInfoLog.setCurdate(TimeUtils.getCurDate());
            long totalInterestRate=CommonUtils.getLong(loaninfovo.getTotalInterestRate())+CommonUtils.getLong(loaninfovo.getTotalInterestFee())+
                    CommonUtils.getLong(loaninfovo.getTotalInterestRenewedFee())+CommonUtils.getLong(loaninfovo.getTotalInterestRenewedRate())
                    +CommonUtils.getLong(loaninfovo.getTotalInterestPenalty());
            loanInfoLog.setTotalInterestRate(new Long(totalInterestRate).toString());
            loanInfoLog.setTotalPayBackAmount(loaninfovo.getTotalPayBackAmount());
            loanInfoLog.setTotalNotPaybackAmount(loaninfovo.getTotalNotPaybackAmount());
            loanInfoLog.setTotalLoanAmount(loaninfovo.getTotalLoanAmount());
            long totalnotbackrate=CommonUtils.getLong(loaninfovo.getTotalNotPaybackRate())+CommonUtils.getLong(loaninfovo.getTotalNotPaybackFee())+
                    CommonUtils.getLong(loaninfovo.getTotalNotPaybackPenalty())+
                    CommonUtils.getLong(loaninfovo.getTotalNotPaybackRenewedFee())+CommonUtils.getLong(loaninfovo.getTotalNotPaybackRenewedRate());
            loanInfoLog.setTotalNotPaybackRate(new Long(totalnotbackrate).toString());
            loanInfoLog.setTotalNotPaybackRenewedAmount(loaninfovo.getTotalNotPaybackRenewedAmount());
            loanInfoLog.setTotalPaybackRenewedAmount(loaninfovo.getTotalPaybackRenewedAmount());
            tbSLLoanInfoLogService.insertTbSlLoanInfo(loanInfoLog);
            tbSlLoanFloatService.insertBatch(addlist);
        }
        }
    }

    @Override
    public List<TbSlPlatformUserWithdrawVO> queryCanLoadByFirstTrail(int joinid) throws BusinessException {
        List<TbSlPlatformUserWithdrawVO> listByJoinuserId = tbSlPlatformUserService.selectPlatformUserWithdrawListByJoinuserId(joinid);
        if(!CommonUtils.isEmpty(listByJoinuserId)){
            for(TbSlPlatformUserWithdrawVO vo:listByJoinuserId){
                long amount=getMaxByPlatformForFisttrial(vo);
                vo.setAvailableCredit(amount);
            }
        }
        return listByJoinuserId;
    }

    @Override
    public void exportSLContractInfoCheckExl(int joinuserid, OutputStream outputStream) throws BusinessException {
    	TbSlLoanApplication applyvo = slservice.queryTbSlApplicationByJoinId(joinuserid);
		
    	SlContractInfoCheckReport reportvo = new SlContractInfoCheckReport();
    	reportvo.setCreditEndDate(applyvo.getCreditEndDate());
    	
		try {
			ExcelTmpl et= new ExcelTmpl(ISLConstDef.SLLOANEXCEL_REPORT_CONSTACTINFOCHECK, outputStream);
			et.wrapData(reportvo);
			et.closeWbook();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
    }

    @Override
    public void updateForCancelCreditInfo(Integer processid) throws BusinessException {
        tbSlLoanCreditService.updateForCancelCredit(processid);
        Map<String,Object> map=new HashMap();
        map.put("id",processid);
        map.put("loanStatus",IConstDef.LOAN_TYPE_OF_CANCEL);
        tbSlProcessInfoService.updateTbSlProcessInfo(map);
    }

    @Override
    public void updateForUploadFile(Integer processid, String ts, String filepath) throws BusinessException {
        tbSlProcessInfoService.lockById(processid);
        dataVersionValidationService.validateVO(processid,"tb_sl_process_info",ts);
        tbSlLoanCreditService.updateFileByProcessid(processid,filepath);
        Map<String,Object> map=new HashMap<>();
        map.put("id",processid);
        map.put("applyDate", TimeUtils.getCurDate());
        map.put("loanStatus",IConstDef.LOAN_TYPE_OF_APPLICATION);
        tbSlProcessInfoService.updateTbSlProcessInfo(map);
        uploadFileService.updateStatusById(CommonUtils.getInt(filepath),IConstDef.UPLOADSTATUS_COMMITED);
    }

    @Override
    public void updateForRejectCredit(Integer processid) throws BusinessException {
        Map<String,Object> parammap=new HashMap<>();
        parammap.put("process_info_id",processid);
        parammap.put("creditstatus", IConstDef.LOAN_TYPE_OF_APPLICATION);
        tbSlLoanCreditService.updateCreditLogForBatch(parammap);
        Map<String,Object> map=new HashMap<>();
        map.put("id",processid);
        map.put("loanStatus",IConstDef.LOAN_TYPE_OF_APPLICATION);
        tbSlProcessInfoService.updateTbSlProcessInfo(map);
    }

    @Override
    public void updateForRefuseCredit(Integer processid,String memo,String ts) throws BusinessException {
        tbSlProcessInfoService.lockById(processid);
        dataVersionValidationService.validateVO(processid,"tb_sl_process_info",ts);
        Map<String,Object> parammap=new HashMap<>();
        parammap.put("process_info_id",processid);
        parammap.put("creditstatus", IConstDef.LOAN_TYPE_OF_REFUSE);
        tbSlLoanCreditService.updateCreditLogForBatch(parammap);
        Map<String,Object> map=new HashMap<>();
        map.put("id",processid);
        map.put("loanStatus",IConstDef.LOAN_TYPE_OF_REFUSE);
        map.put("memo",memo);
        tbSlProcessInfoService.updateTbSlProcessInfo(map);
        if(!CommonUtils.isDev()){
        TbSlProcessInfoVO processInfoVO=tbSlProcessInfoService.queryMobileByProcessid(processid);
        if(!CommonUtils.isEmpty(processInfoVO)){
            String mobile=processInfoVO.getMobile();
            if(!CommonUtils.isEmpty(mobile)){
            	sendMsg("%applydate%", processInfoVO.getApplyDate(), ISLConstDef.LOAN_REFUSE, mobile);
            }
        }
        }

    }

    @Override
    public void updateRechargeAccount(Integer id,String msg) throws BusinessException {
        try{
            TbTransferTokenStatus info=transferTokenStatusService.queryById(id);
            String token=info.getToken();
            transferTokenStatusService.updateTransferTokenStatus(token,IConstDef.TRANSFERSTATUS_FAILED,msg);
            List rechargelist= this.accountbaseservice.rechargeAccountBalanceNoPwd(info.getFromIdOfPaynow(),info.getAccTypeFrom(),info.getToIdOfPaynow(),info.getAccTypeTo(),info.getAmount(),"重新还款，上次还款的id"+id,UUIDUtils.create());
        }catch (Exception e){
           if(e instanceof  BusinessException){
               throw e ;
           }
           else throw new BusinessException("重新转账失败");

        }
    }

    @Override
    public void updateForDealRedoWithFailure(String orderId,String msg) throws BusinessException {

        TransferErrorStatusInfo info=transferTokenStatusService.queryByToken(orderId);
        TbRedo redo=tbRedoService.queryTbReDoByBusinessId(orderId);

        String mobile=info.getFromMhtmobile();
        String businesstype="";
        if("0".equals(redo.getBusinessType())||"1".equals(redo.getBusinessType())){
            businesstype="还款";
        }
        if("2".equals(redo.getBusinessType())){
            mobile="13810958662";
        }
        if(!CommonUtils.isEmpty(mobile)&&!CommonUtils.isDev()){
        	sendMsg("%operate%", redo.getApplyDate()+businesstype, ISLConstDef.OPERATE_ERROR, mobile);
        }
        transferTokenStatusService.updateTransferTokenStatus(orderId,IConstDef.TRANSFERSTATUS_FAILED,msg);
        tbRedoService.updateTbRedo(orderId);
        TbMerchantuserExceptionorder ordervo=new TbMerchantuserExceptionorder();
        ordervo.setHandleTime(TimeUtils.getCurDateTime());
        ordervo.setHandleMemo("处理完毕");
        ordervo.setOrderid(orderId);
        ordervo.setAccountStatus(IConstDef.ACCOUNT_STATUS_UNFREEZE);
        merchantuserExceptionorderBaseService.updateVOByOrderId(ordervo);
    }

	@Override
	public void exportSLDailyLoanFile(String curdate, Integer idOfTbMerchantUser, Integer joinuserid, OutputStream outputStream)
			throws BusinessException {
		List<TbSlLoanDailyBillVo> loanDailyBillVos=tbSlLoanInfoService.queryDailyBill(curdate, idOfTbMerchantUser, joinuserid, null);
		String queryDailySum = tbSlLoanInfoService.queryDailySum(curdate, idOfTbMerchantUser, joinuserid);
		
		if (loanDailyBillVos != null && loanDailyBillVos.size() > 0) {
			for(TbSlLoanDailyBillVo vo :loanDailyBillVos) {
				vo.setTotalNotPayBackAmount(CommonUtils.getFenByString(vo.getTotalNotPayBackAmount()));
			}
		}
		
		SlDailyReportVO reportvo = new SlDailyReportVO();
		reportvo.setDailydetaillist(loanDailyBillVos);
		reportvo.setDailytotalamount(CommonUtils.getFenByString(queryDailySum));
		
		try {
			ExcelTmpl et = new ExcelTmpl(ISLConstDef.SLLOANEXCEL_REPORT_DAILYLOAN, outputStream);
			et.wrapData(reportvo);
			et.closeWbook();
			
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void manualPartRefund(int joinid,List<TbSlNotPayBackCredit> listvo,TbSlLoanInfo loaninfovo,String pwd,String accamount, String repayAcccountType)
			throws BusinessException {
		boolean isfrezz=merchantuserExceptionorderBaseService.isFreezeByJoinuserID(joinid);
		if(isfrezz){
	        throw new BusinessException("账户状态为锁定，请联系保理公司");
	    }

        if(isDaySpecial()){
            throw new BusinessException("节假日期间不能还款");
        }
        
        if(!CommonUtils.expireTime()){
            throw new BusinessException("请于当日下午15:00前还款");
        }
        
        if(CommonUtils.isEmpty(joinid)||CommonUtils.isEmpty(listvo)) {
        	throw new BusinessException("未选择还款记录");
        }
        
		Long refundamount = this.updateForRepayLoan(joinid,listvo,loaninfovo ,pwd,accamount, IConstDef.ACCTYPE_FINANCING);
        
//        String restAmount = CommonUtils.getString(CommonUtils.getLong(accamount) - refundamount);
//        
//        TbSlLoanCreditLog creditLog=tbSlLoanCreditService.queryCreditLogById(listvo.get(0).getId());
//        String userIdOfIPayNowOfDebtor = creditLog.getUserIdOfIPayNowOfDebtor();
//        
//        if(!CommonUtils.isDev()) {
//	        String orderId = UUIDUtils.create();
//	        accountbaseservice.rechargeAccountBalanceNoPwd(
//	        		userIdOfIPayNowOfDebtor, IConstDef.ACCTYPE_FINANCING, 
//	        		userIdOfIPayNowOfDebtor, IConstDef.ACCTYPE_BASE, 
//	        		restAmount, "还款剩余金额", orderId);
//        }
	}
	

}

